From 81b33b503d6dc8b6f18cb4b5f37abb51a276c8f7 Mon Sep 17 00:00:00 2001 From: Mostafa Moradian Date: Wed, 5 Aug 2026 21:41:06 +0200 Subject: [PATCH 01/28] chore(deps): Add cilium/ebpf dependency Pull in cilium/ebpf v0.20.0 for the Linux CO-RE instrumentation spike and future event source work. --- go.mod | 15 ++++++++------- go.sum | 30 ++++++++++++++++-------------- 2 files changed, 24 insertions(+), 21 deletions(-) diff --git a/go.mod b/go.mod index 8510793f0..f4c2afb44 100644 --- a/go.mod +++ b/go.mod @@ -37,8 +37,8 @@ require ( github.com/zeebo/xxh3 v1.1.0 go.mozilla.org/pkcs7 v0.0.0-20210826202110-33d05740a352 golang.org/x/arch v0.6.0 - golang.org/x/sys v0.31.0 - golang.org/x/text v0.23.0 + golang.org/x/sys v0.37.0 + golang.org/x/text v0.30.0 golang.org/x/time v0.3.0 gopkg.in/gomail.v2 v2.0.0-20160411212932-81ebce5c23df gopkg.in/natefinch/lumberjack.v2 v2.0.0 @@ -50,13 +50,14 @@ require ( github.com/klauspost/cpuid/v2 v2.2.10 // indirect github.com/kr/pretty v0.3.1 // indirect github.com/rivo/uniseg v0.4.2 // indirect - github.com/rogpeppe/go-internal v1.11.0 // indirect + github.com/rogpeppe/go-internal v1.12.0 // indirect github.com/secDre4mer/pkcs7 v0.0.0-20240322103146-665324a4461d // indirect go4.org/netipx v0.0.0-20220725152314-7e7bdc8411bf // indirect golang.org/x/exp/typeparams v0.0.0-20220218215828-6cf2b201936e // indirect - golang.org/x/mod v0.17.0 // indirect + golang.org/x/mod v0.29.0 // indirect golang.org/x/sync v0.21.0 // indirect - golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d // indirect + golang.org/x/tools v0.38.0 // indirect + golang.org/x/tools/go/expect v0.1.1-deprecated // indirect gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect honnef.co/go/tools v0.3.2 // indirect ) @@ -91,8 +92,8 @@ require ( github.com/subosito/gotenv v1.2.0 // indirect github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f // indirect github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect - golang.org/x/crypto v0.36.0 // indirect - golang.org/x/net v0.38.0 // indirect + golang.org/x/crypto v0.43.0 // indirect + golang.org/x/net v0.46.0 // indirect gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc // indirect gopkg.in/ini.v1 v1.51.0 // indirect gopkg.in/yaml.v2 v2.3.0 // indirect diff --git a/go.sum b/go.sum index dc48d1a7d..434b3bfea 100644 --- a/go.sum +++ b/go.sum @@ -178,8 +178,8 @@ github.com/rivo/uniseg v0.4.2 h1:YwD0ulJSJytLpiaWua0sBDusfsCZohxjxzVTYjwxfV8= github.com/rivo/uniseg v0.4.2/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88= github.com/rogpeppe/fastuuid v0.0.0-20150106093220-6724a57986af/go.mod h1:XWv6SoW27p1b0cqNHllgS5HIMJraePCO15w5zCzIWYg= github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= -github.com/rogpeppe/go-internal v1.11.0 h1:cWPaGQEPrBb5/AsnsZesgZZ9yb1OQ+GOISoDNXVBh4M= -github.com/rogpeppe/go-internal v1.11.0/go.mod h1:ddIwULY96R17DhadqLgMfk9H9tvdUzkipdSkR5nkCZA= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= github.com/saferwall/pe v1.5.6 h1:DrRLnoQFxHWJ5lJUmrH7X2L0xeUu6SUS95Dc61eW2Yc= github.com/saferwall/pe v1.5.6/go.mod h1:mJx+PuptmNpoPFBNhWs/uDMFL/kTHVZIkg0d4OUJFbQ= github.com/secDre4mer/pkcs7 v0.0.0-20240322103146-665324a4461d h1:RQqyEogx5J6wPdoxqL132b100j8KjcVHO1c0KLRoIhc= @@ -273,8 +273,8 @@ golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnf golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20200414173820-0848c9571904/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= -golang.org/x/crypto v0.36.0 h1:AnAEvhDddvBdpY+uR+MyHmuZzzNqXSe/GvuDeob5L34= -golang.org/x/crypto v0.36.0/go.mod h1:Y4J0ReaxCR1IMaabaSMugxJES1EpwhBHhv2bDHklZvc= +golang.org/x/crypto v0.43.0 h1:dduJYIi3A3KOfdGOHX8AVZ/jGiyPa3IbBozJ5kNuE04= +golang.org/x/crypto v0.43.0/go.mod h1:BFbav4mRNlXJL4wNeejLpWxB7wMbc79PdRGhWKncxR0= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp/typeparams v0.0.0-20220218215828-6cf2b201936e h1:qyrTQ++p1afMkO4DPEeLGq/3oTsdlvdH4vqZUBWzUKM= golang.org/x/exp/typeparams v0.0.0-20220218215828-6cf2b201936e/go.mod h1:AbB0pIl9nAr9wVwH+Z2ZpaocVmF5I4GyWCDIsVjR0bk= @@ -282,8 +282,8 @@ golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTk golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= -golang.org/x/mod v0.17.0 h1:zY54UmvipHiNd+pm+m0x9KhZ9hl1/7QNMyxXbc6ICqA= -golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= +golang.org/x/mod v0.29.0 h1:HV8lRxZC4l2cr3Zq1LvtOsi/ThTgWnUk/y64QSs8GwA= +golang.org/x/mod v0.29.0/go.mod h1:NyhrlYXJ2H4eJiRy/WDBO6HMqZQ6q9nk4JzS3NuCK+w= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -297,8 +297,8 @@ golang.org/x/net v0.0.0-20200202094626-16171245cfb2/go.mod h1:z5CRVTTTmAJ677TzLL golang.org/x/net v0.0.0-20200421231249-e086a090c8fd/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= -golang.org/x/net v0.38.0 h1:vRMAPTMaeGqVhG5QyLJHqNDwecKTomGeqbnfZyKlBI8= -golang.org/x/net v0.38.0/go.mod h1:ivrbrMbzFq5J41QOQh0siUuly180yBYtLp+CKbEaFx8= +golang.org/x/net v0.46.0 h1:giFlY12I07fugqwPuWJi68oOnpfqFnJIJzaIIm2JVV4= +golang.org/x/net v0.46.0/go.mod h1:Q9BGdFy1y4nkUwiLvT5qtyhAnEHgnQ/zd8PfU6nc210= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= @@ -326,8 +326,8 @@ golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.31.0 h1:ioabZlmFYtWhL+TRYpcnNlLwhyxaM9kWTDEmfnprqik= -golang.org/x/sys v0.31.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= +golang.org/x/sys v0.37.0 h1:fdNQudmxPjkdUTPnLn5mdQv7Zwvbvpaxqs831goi9kQ= +golang.org/x/sys v0.37.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= @@ -336,8 +336,8 @@ golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= -golang.org/x/text v0.23.0 h1:D71I7dUrlY+VX0gQShAThNGHFxZ13dGLBHQLVl1mJlY= -golang.org/x/text v0.23.0/go.mod h1:/BLNzu4aZCJ1+kcD0DNRotWKage4q2rGVAg4o22unh4= +golang.org/x/text v0.30.0 h1:yznKA/E9zq54KzlzBEAWn1NXSQ8DIp/NYMy88xJjl4k= +golang.org/x/text v0.30.0/go.mod h1:yDdHFIX9t+tORqspjENWgzaCVXgk0yYnYuSZ8UzzBVM= golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.3.0 h1:rg5rLMjNzMS1RkNLzCG38eapWhnYLFYXDXj2gOlr8j4= golang.org/x/time v0.3.0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= @@ -349,8 +349,10 @@ golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3 golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= -golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d h1:vU5i/LfpvrRCpgM/VPfJLg5KjxD3E+hfT1SH+d9zLwg= -golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk= +golang.org/x/tools v0.38.0 h1:Hx2Xv8hISq8Lm16jvBZ2VQf+RLmbd7wVUsALibYI/IQ= +golang.org/x/tools v0.38.0/go.mod h1:yEsQ/d/YK8cjh0L6rZlY8tgtlKiBNTL14pGDJPJpYQs= +golang.org/x/tools/go/expect v0.1.1-deprecated h1:jpBZDwmgPhXsKZC6WhL20P4b/wmnpsEAGHaNy0n/rJM= +golang.org/x/tools/go/expect v0.1.1-deprecated/go.mod h1:eihoPOH+FgIqa3FpoTwguz/bVUSGBlGQU67vpBeOrBY= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= From 12c606a3af64290dfd64b3cdfaf6744775740946 Mon Sep 17 00:00:00 2001 From: Mostafa Moradian Date: Wed, 5 Aug 2026 21:41:06 +0200 Subject: [PATCH 02/28] chore(ebpf): Add feature probes and race-safe process reconciler Encode the hard Linux runtime contract (kernel >=5.9, runtime BTF, ringbuf, tracing/iter support) and prototype ProcessKey-based startup reconciliation with bounded pending-queue and drop metrics. --- internal/ebpf/doc.go | 22 ++++ internal/ebpf/features.go | 167 ++++++++++++++++++++++++ internal/ebpf/features_test.go | 43 ++++++ internal/ebpf/reconcile.go | 223 ++++++++++++++++++++++++++++++++ internal/ebpf/reconcile_test.go | 86 ++++++++++++ 5 files changed, 541 insertions(+) create mode 100644 internal/ebpf/doc.go create mode 100644 internal/ebpf/features.go create mode 100644 internal/ebpf/features_test.go create mode 100644 internal/ebpf/reconcile.go create mode 100644 internal/ebpf/reconcile_test.go diff --git a/internal/ebpf/doc.go b/internal/ebpf/doc.go new file mode 100644 index 000000000..6b50b1917 --- /dev/null +++ b/internal/ebpf/doc.go @@ -0,0 +1,22 @@ +/* + * Copyright 2026 Fibratus contributors + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Package ebpf hosts the Linux eBPF instrumentation backend and supporting +// feasibility prototypes used to validate CO-RE load, feature probes, and +// race-safe process-state reconciliation. +package ebpf diff --git a/internal/ebpf/features.go b/internal/ebpf/features.go new file mode 100644 index 000000000..8ef430124 --- /dev/null +++ b/internal/ebpf/features.go @@ -0,0 +1,167 @@ +//go:build linux + +/* + * Copyright 2026 Fibratus contributors + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ebpf + +import ( + "errors" + "fmt" + "os" + "strings" + + "github.com/cilium/ebpf" + "github.com/cilium/ebpf/asm" + "github.com/cilium/ebpf/features" + "golang.org/x/sys/unix" +) + +const ( + // MinKernelVersion is the hard policy floor for the Linux eBPF backend. + // BPF task iterators require Linux 5.9. bpf_d_path is intentionally unused + // because it only appears in 5.10+. + MinKernelVersion = "5.9" + + kernelBTFPath = "/sys/kernel/btf/vmlinux" +) + +// PrerequisiteReport captures runtime probe results for the Linux eBPF backend. +type PrerequisiteReport struct { + KernelRelease string + KernelOK bool + BTFPath string + BTFOK bool + RingbufOK bool + TracingOK bool + IterOK bool + RingbufHelper bool + Errors []string +} + +// ProbePrerequisites verifies the hard runtime contract for the Linux eBPF backend. +// Missing features produce an error; there is no BTFHub or build-host BTF fallback. +func ProbePrerequisites() (*PrerequisiteReport, error) { + report := &PrerequisiteReport{BTFPath: kernelBTFPath} + + var uts unix.Utsname + if err := unix.Uname(&uts); err != nil { + return nil, fmt.Errorf("reading kernel release: %w", err) + } + report.KernelRelease = unix.ByteSliceToString(uts.Release[:]) + + if err := checkKernelVersion(report.KernelRelease, MinKernelVersion); err != nil { + report.Errors = append(report.Errors, err.Error()) + } else { + report.KernelOK = true + } + + if st, err := os.Stat(kernelBTFPath); err != nil || st.IsDir() || st.Size() == 0 { + report.Errors = append(report.Errors, fmt.Sprintf("usable kernel BTF required at %s", kernelBTFPath)) + } else { + report.BTFOK = true + } + + if err := features.HaveMapType(ebpf.RingBuf); err != nil { + report.Errors = append(report.Errors, fmt.Sprintf("ring buffer maps unavailable: %v", err)) + } else { + report.RingbufOK = true + } + + if err := features.HaveProgramType(ebpf.TracePoint); err != nil { + report.Errors = append(report.Errors, fmt.Sprintf("tracepoint programs unavailable: %v", err)) + } + if err := features.HaveProgramType(ebpf.Tracing); err != nil { + report.Errors = append(report.Errors, fmt.Sprintf("tracing programs unavailable: %v", err)) + } else { + report.TracingOK = true + } + + // Helper probes are program-type specific in cilium/ebpf. TracePoint covers the + // hot-path helpers; Tracing covers the iterator program class. + if err := features.HaveProgramHelper(ebpf.TracePoint, asm.FnGetCurrentTask); err != nil { + report.Errors = append(report.Errors, fmt.Sprintf("bpf_get_current_task helper unavailable: %v", err)) + } + if err := features.HaveProgramHelper(ebpf.TracePoint, asm.FnRingbufReserve); err != nil { + report.Errors = append(report.Errors, fmt.Sprintf("ringbuf helpers unavailable: %v", err)) + } else { + report.RingbufHelper = true + } + + // Task iterators attach as Tracing + AttachTraceIter against a kernel BTF target. + if report.TracingOK && report.BTFOK { + report.IterOK = true + } else { + report.Errors = append(report.Errors, "iter/task requires tracing programs and runtime kernel BTF") + } + + if len(report.Errors) > 0 { + return report, errors.New(strings.Join(report.Errors, "; ")) + } + return report, nil +} + +func checkKernelVersion(current, minimum string) error { + cur, err := parseKernelVersion(current) + if err != nil { + return fmt.Errorf("parsing kernel version %q: %w", current, err) + } + min, err := parseKernelVersion(minimum) + if err != nil { + return fmt.Errorf("parsing minimum kernel version %q: %w", minimum, err) + } + if compareKernelVersion(cur, min) < 0 { + return fmt.Errorf("kernel %s is below required %s", current, minimum) + } + return nil +} + +type kernelVersion struct { + major int + minor int + patch int +} + +func parseKernelVersion(v string) (kernelVersion, error) { + v = strings.SplitN(v, "-", 2)[0] + parts := strings.Split(v, ".") + if len(parts) < 2 { + return kernelVersion{}, fmt.Errorf("invalid version %q", v) + } + var kv kernelVersion + if _, err := fmt.Sscanf(parts[0], "%d", &kv.major); err != nil { + return kernelVersion{}, err + } + if _, err := fmt.Sscanf(parts[1], "%d", &kv.minor); err != nil { + return kernelVersion{}, err + } + if len(parts) > 2 { + _, _ = fmt.Sscanf(parts[2], "%d", &kv.patch) + } + return kv, nil +} + +func compareKernelVersion(a, b kernelVersion) int { + if a.major != b.major { + return a.major - b.major + } + if a.minor != b.minor { + return a.minor - b.minor + } + return a.patch - b.patch +} diff --git a/internal/ebpf/features_test.go b/internal/ebpf/features_test.go new file mode 100644 index 000000000..430767e2d --- /dev/null +++ b/internal/ebpf/features_test.go @@ -0,0 +1,43 @@ +//go:build linux + +/* + * Copyright 2026 Fibratus contributors + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ebpf + +import "testing" + +func TestCheckKernelVersion(t *testing.T) { + tests := []struct { + current string + minimum string + wantErr bool + }{ + {current: "5.9.0", minimum: "5.9", wantErr: false}, + {current: "5.10.1", minimum: "5.9", wantErr: false}, + {current: "6.12.76-linuxkit", minimum: "5.9", wantErr: false}, + {current: "5.8.18", minimum: "5.9", wantErr: true}, + {current: "4.18.0-553.el8", minimum: "5.9", wantErr: true}, + } + for _, tt := range tests { + err := checkKernelVersion(tt.current, tt.minimum) + if (err != nil) != tt.wantErr { + t.Fatalf("checkKernelVersion(%q, %q) err=%v wantErr=%v", tt.current, tt.minimum, err, tt.wantErr) + } + } +} diff --git a/internal/ebpf/reconcile.go b/internal/ebpf/reconcile.go new file mode 100644 index 000000000..31184d0d6 --- /dev/null +++ b/internal/ebpf/reconcile.go @@ -0,0 +1,223 @@ +/* + * Copyright 2026 Fibratus contributors + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ebpf + +import ( + "fmt" + "sync" + "sync/atomic" +) + +// ProcessKey uniquely identifies a process instance across PID reuse. +type ProcessKey struct { + PID uint32 + StartBootTime uint64 +} + +// HotEvent is a timestamped ring-buffer record received while the task +// iterator baseline is still being established. +type HotEvent struct { + Key ProcessKey + Kind uint32 + Timestamp uint64 + Comm string + Filename string + ExePath string + Cmdline string +} + +// Metrics accounts for every pressure-induced drop during startup/live capture. +type Metrics struct { + PendingQueued atomic.Uint64 + PendingDropped atomic.Uint64 + RingbufDropped atomic.Uint64 + EnrichmentMiss atomic.Uint64 + ReplayApplied atomic.Uint64 + SnapshotUpserts atomic.Uint64 +} + +// ProcessRecord is the reconciled userspace view of a process instance. +type ProcessRecord struct { + Key ProcessKey + Comm string + Filename string + ExePath string + Cmdline string + FromSnap bool + FromHot bool +} + +// StartupReconciler prototypes the race-safe startup sequence: +// queue hot events, upsert iterator baseline by ProcessKey, replay pending +// events idempotently, then switch to live updates. +type StartupReconciler struct { + mu sync.Mutex + pending []HotEvent + live bool + capacity int + procs map[ProcessKey]*ProcessRecord + Metrics Metrics +} + +// NewStartupReconciler creates a reconciler with a bounded pending queue. +func NewStartupReconciler(capacity int) *StartupReconciler { + if capacity <= 0 { + capacity = 1024 + } + return &StartupReconciler{ + capacity: capacity, + procs: make(map[ProcessKey]*ProcessRecord), + } +} + +// EnqueueHot queues a hot event while baseline capture is in progress. +// Returns false when the bounded queue drops the event. +func (r *StartupReconciler) EnqueueHot(ev HotEvent) bool { + r.mu.Lock() + defer r.mu.Unlock() + if r.live { + r.applyLocked(ev, true) + return true + } + if len(r.pending) >= r.capacity { + r.Metrics.PendingDropped.Add(1) + return false + } + r.pending = append(r.pending, ev) + r.Metrics.PendingQueued.Add(1) + return true +} + +// UpsertSnapshot installs an iterator baseline record keyed by ProcessKey. +func (r *StartupReconciler) UpsertSnapshot(rec ProcessRecord) { + r.mu.Lock() + defer r.mu.Unlock() + rec.FromSnap = true + existing, ok := r.procs[rec.Key] + if !ok { + cp := rec + r.procs[rec.Key] = &cp + r.Metrics.SnapshotUpserts.Add(1) + return + } + mergeSnapshot(existing, rec) + r.Metrics.SnapshotUpserts.Add(1) +} + +// FinishBaseline replays queued hot events in order and switches to live mode. +func (r *StartupReconciler) FinishBaseline() { + r.mu.Lock() + defer r.mu.Unlock() + for _, ev := range r.pending { + r.applyLocked(ev, true) + r.Metrics.ReplayApplied.Add(1) + } + r.pending = nil + r.live = true +} + +// Get returns the reconciled process record for key, if present. +func (r *StartupReconciler) Get(key ProcessKey) (ProcessRecord, bool) { + r.mu.Lock() + defer r.mu.Unlock() + rec, ok := r.procs[key] + if !ok { + return ProcessRecord{}, false + } + return *rec, true +} + +// Size returns the number of reconciled process records. +func (r *StartupReconciler) Size() int { + r.mu.Lock() + defer r.mu.Unlock() + return len(r.procs) +} + +// AccountRingbufDrop records a ring-buffer reserve failure observed in-kernel. +func (r *StartupReconciler) AccountRingbufDrop(n uint64) { + if n == 0 { + return + } + r.Metrics.RingbufDropped.Add(n) +} + +// AccountEnrichmentMiss records a failed best-effort /proc enrichment. +func (r *StartupReconciler) AccountEnrichmentMiss() { + r.Metrics.EnrichmentMiss.Add(1) +} + +func (r *StartupReconciler) applyLocked(ev HotEvent, fromHot bool) { + rec, ok := r.procs[ev.Key] + if !ok { + r.procs[ev.Key] = &ProcessRecord{ + Key: ev.Key, + Comm: ev.Comm, + Filename: ev.Filename, + ExePath: ev.ExePath, + Cmdline: ev.Cmdline, + FromHot: fromHot, + } + return + } + if ev.Comm != "" { + rec.Comm = ev.Comm + } + if ev.Filename != "" { + rec.Filename = ev.Filename + } + if ev.ExePath != "" { + rec.ExePath = ev.ExePath + } + if ev.Cmdline != "" { + rec.Cmdline = ev.Cmdline + } + if fromHot { + rec.FromHot = true + } +} + +func mergeSnapshot(dst *ProcessRecord, src ProcessRecord) { + dst.FromSnap = true + if src.Comm != "" { + dst.Comm = src.Comm + } + if src.Filename != "" { + dst.Filename = src.Filename + } + if src.ExePath != "" { + dst.ExePath = src.ExePath + } + if src.Cmdline != "" { + dst.Cmdline = src.Cmdline + } +} + +// String returns a compact metrics summary for spike diagnostics. +func (m *Metrics) String() string { + return fmt.Sprintf( + "pending_queued=%d pending_dropped=%d ringbuf_dropped=%d enrichment_miss=%d replay_applied=%d snapshot_upserts=%d", + m.PendingQueued.Load(), + m.PendingDropped.Load(), + m.RingbufDropped.Load(), + m.EnrichmentMiss.Load(), + m.ReplayApplied.Load(), + m.SnapshotUpserts.Load(), + ) +} diff --git a/internal/ebpf/reconcile_test.go b/internal/ebpf/reconcile_test.go new file mode 100644 index 000000000..3e8c7031a --- /dev/null +++ b/internal/ebpf/reconcile_test.go @@ -0,0 +1,86 @@ +/* + * Copyright 2026 Fibratus contributors + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ebpf + +import "testing" + +func TestStartupReconcilerRaceSafeBaseline(t *testing.T) { + r := NewStartupReconciler(8) + + keyA := ProcessKey{PID: 42, StartBootTime: 100} + keyB := ProcessKey{PID: 42, StartBootTime: 200} // PID reuse with different start time + + if !r.EnqueueHot(HotEvent{Key: keyA, Kind: 1, Comm: "hot-a", Filename: "/bin/hot-a"}) { + t.Fatal("expected hot event to be queued") + } + + r.UpsertSnapshot(ProcessRecord{Key: keyA, Comm: "snap-a"}) + r.UpsertSnapshot(ProcessRecord{Key: keyB, Comm: "snap-b"}) + r.FinishBaseline() + + gotA, ok := r.Get(keyA) + if !ok { + t.Fatal("missing keyA after baseline") + } + if gotA.Comm != "hot-a" { + t.Fatalf("keyA comm=%q want hot-a (hot replay should win over snapshot comm)", gotA.Comm) + } + if gotA.Filename != "/bin/hot-a" { + t.Fatalf("keyA filename=%q", gotA.Filename) + } + if !gotA.FromSnap || !gotA.FromHot { + t.Fatalf("keyA flags snap=%v hot=%v", gotA.FromSnap, gotA.FromHot) + } + + gotB, ok := r.Get(keyB) + if !ok { + t.Fatal("missing keyB after baseline") + } + if gotB.Comm != "snap-b" { + t.Fatalf("keyB comm=%q want snap-b", gotB.Comm) + } + + // Live update for reused PID must not clobber the other instance. + r.EnqueueHot(HotEvent{Key: keyB, Kind: 1, Comm: "live-b", ExePath: "/bin/live-b"}) + gotB, _ = r.Get(keyB) + if gotB.Comm != "live-b" || gotB.ExePath != "/bin/live-b" { + t.Fatalf("live update failed: %+v", gotB) + } + gotA, _ = r.Get(keyA) + if gotA.Comm != "hot-a" { + t.Fatalf("PID reuse clobbered keyA: %+v", gotA) + } +} + +func TestStartupReconcilerPendingBackpressure(t *testing.T) { + r := NewStartupReconciler(2) + key := ProcessKey{PID: 1, StartBootTime: 1} + if !r.EnqueueHot(HotEvent{Key: key, Kind: 1}) { + t.Fatal("first enqueue failed") + } + if !r.EnqueueHot(HotEvent{Key: key, Kind: 1}) { + t.Fatal("second enqueue failed") + } + if r.EnqueueHot(HotEvent{Key: key, Kind: 1}) { + t.Fatal("expected bounded queue drop") + } + if r.Metrics.PendingDropped.Load() != 1 { + t.Fatalf("pending_dropped=%d want 1", r.Metrics.PendingDropped.Load()) + } +} From 41542374b0632a85bf2580693931cbee5d8ded9c Mon Sep 17 00:00:00 2001 From: Mostafa Moradian Date: Wed, 5 Aug 2026 21:41:07 +0200 Subject: [PATCH 03/28] chore(ebpf): Add CO-RE spike for exec and task iterator Prove sched_process_exec ringbuf capture, iter/task baseline without bpf_d_path, shared-map replacement across separately generated objects, best-effort /proc enrichment, and race-safe startup on a real kernel. --- internal/ebpf/spike/c/LICENSE.BSD-2-Clause | 32 + internal/ebpf/spike/c/bpf_core_read.h | 561 +++ internal/ebpf/spike/c/bpf_endian.h | 99 + internal/ebpf/spike/c/bpf_helper_defs.h | 4139 ++++++++++++++++++++ internal/ebpf/spike/c/bpf_helpers.h | 262 ++ internal/ebpf/spike/c/bpf_tracing.h | 492 +++ internal/ebpf/spike/c/events.h | 49 + internal/ebpf/spike/c/execve.bpf.c | 53 + internal/ebpf/spike/c/proc_iter.bpf.c | 63 + internal/ebpf/spike/c/vmlinux.h | 149 + internal/ebpf/spike/cmd/spike/main.go | 47 + internal/ebpf/spike/enrich.go | 53 + internal/ebpf/spike/event.go | 35 + internal/ebpf/spike/execve_bpfeb.go | 136 + internal/ebpf/spike/execve_bpfeb.o | Bin 0 -> 6960 bytes internal/ebpf/spike/execve_bpfel.go | 136 + internal/ebpf/spike/execve_bpfel.o | Bin 0 -> 6960 bytes internal/ebpf/spike/gen.go | 26 + internal/ebpf/spike/generate.sh | 34 + internal/ebpf/spike/prociter_bpfeb.go | 136 + internal/ebpf/spike/prociter_bpfeb.o | Bin 0 -> 5592 bytes internal/ebpf/spike/prociter_bpfel.go | 136 + internal/ebpf/spike/prociter_bpfel.o | Bin 0 -> 5592 bytes internal/ebpf/spike/run.go | 290 ++ 24 files changed, 6928 insertions(+) create mode 100644 internal/ebpf/spike/c/LICENSE.BSD-2-Clause create mode 100644 internal/ebpf/spike/c/bpf_core_read.h create mode 100644 internal/ebpf/spike/c/bpf_endian.h create mode 100644 internal/ebpf/spike/c/bpf_helper_defs.h create mode 100644 internal/ebpf/spike/c/bpf_helpers.h create mode 100644 internal/ebpf/spike/c/bpf_tracing.h create mode 100644 internal/ebpf/spike/c/events.h create mode 100644 internal/ebpf/spike/c/execve.bpf.c create mode 100644 internal/ebpf/spike/c/proc_iter.bpf.c create mode 100644 internal/ebpf/spike/c/vmlinux.h create mode 100644 internal/ebpf/spike/cmd/spike/main.go create mode 100644 internal/ebpf/spike/enrich.go create mode 100644 internal/ebpf/spike/event.go create mode 100644 internal/ebpf/spike/execve_bpfeb.go create mode 100644 internal/ebpf/spike/execve_bpfeb.o create mode 100644 internal/ebpf/spike/execve_bpfel.go create mode 100644 internal/ebpf/spike/execve_bpfel.o create mode 100644 internal/ebpf/spike/gen.go create mode 100755 internal/ebpf/spike/generate.sh create mode 100644 internal/ebpf/spike/prociter_bpfeb.go create mode 100644 internal/ebpf/spike/prociter_bpfeb.o create mode 100644 internal/ebpf/spike/prociter_bpfel.go create mode 100644 internal/ebpf/spike/prociter_bpfel.o create mode 100644 internal/ebpf/spike/run.go diff --git a/internal/ebpf/spike/c/LICENSE.BSD-2-Clause b/internal/ebpf/spike/c/LICENSE.BSD-2-Clause new file mode 100644 index 000000000..da366e2ce --- /dev/null +++ b/internal/ebpf/spike/c/LICENSE.BSD-2-Clause @@ -0,0 +1,32 @@ +Valid-License-Identifier: BSD-2-Clause +SPDX-URL: https://spdx.org/licenses/BSD-2-Clause.html +Usage-Guide: + To use the BSD 2-clause "Simplified" License put the following SPDX + tag/value pair into a comment according to the placement guidelines in + the licensing rules documentation: + SPDX-License-Identifier: BSD-2-Clause +License-Text: + +Copyright (c) . All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. diff --git a/internal/ebpf/spike/c/bpf_core_read.h b/internal/ebpf/spike/c/bpf_core_read.h new file mode 100644 index 000000000..c0e13cdf9 --- /dev/null +++ b/internal/ebpf/spike/c/bpf_core_read.h @@ -0,0 +1,561 @@ +/* SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause) */ +#ifndef __BPF_CORE_READ_H__ +#define __BPF_CORE_READ_H__ + +#include "bpf_helpers.h" + +/* + * enum bpf_field_info_kind is passed as a second argument into + * __builtin_preserve_field_info() built-in to get a specific aspect of + * a field, captured as a first argument. __builtin_preserve_field_info(field, + * info_kind) returns __u32 integer and produces BTF field relocation, which + * is understood and processed by libbpf during BPF object loading. See + * selftests/bpf for examples. + */ +enum bpf_field_info_kind { + BPF_FIELD_BYTE_OFFSET = 0, /* field byte offset */ + BPF_FIELD_BYTE_SIZE = 1, + BPF_FIELD_EXISTS = 2, /* field existence in target kernel */ + BPF_FIELD_SIGNED = 3, + BPF_FIELD_LSHIFT_U64 = 4, + BPF_FIELD_RSHIFT_U64 = 5, +}; + +/* second argument to __builtin_btf_type_id() built-in */ +enum bpf_type_id_kind { + BPF_TYPE_ID_LOCAL = 0, /* BTF type ID in local program */ + BPF_TYPE_ID_TARGET = 1, /* BTF type ID in target kernel */ +}; + +/* second argument to __builtin_preserve_type_info() built-in */ +enum bpf_type_info_kind { + BPF_TYPE_EXISTS = 0, /* type existence in target kernel */ + BPF_TYPE_SIZE = 1, /* type size in target kernel */ + BPF_TYPE_MATCHES = 2, /* type match in target kernel */ +}; + +/* second argument to __builtin_preserve_enum_value() built-in */ +enum bpf_enum_value_kind { + BPF_ENUMVAL_EXISTS = 0, /* enum value existence in kernel */ + BPF_ENUMVAL_VALUE = 1, /* enum value value relocation */ +}; + +#define __CORE_RELO(src, field, info) \ + __builtin_preserve_field_info((src)->field, BPF_FIELD_##info) + +#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ +#define __CORE_BITFIELD_PROBE_READ(dst, src, fld) \ + bpf_probe_read_kernel( \ + (void *)dst, \ + __CORE_RELO(src, fld, BYTE_SIZE), \ + (const void *)src + __CORE_RELO(src, fld, BYTE_OFFSET)) +#else +/* semantics of LSHIFT_64 assumes loading values into low-ordered bytes, so + * for big-endian we need to adjust destination pointer accordingly, based on + * field byte size + */ +#define __CORE_BITFIELD_PROBE_READ(dst, src, fld) \ + bpf_probe_read_kernel( \ + (void *)dst + (8 - __CORE_RELO(src, fld, BYTE_SIZE)), \ + __CORE_RELO(src, fld, BYTE_SIZE), \ + (const void *)src + __CORE_RELO(src, fld, BYTE_OFFSET)) +#endif + +/* + * Extract bitfield, identified by s->field, and return its value as u64. + * All this is done in relocatable manner, so bitfield changes such as + * signedness, bit size, offset changes, this will be handled automatically. + * This version of macro is using bpf_probe_read_kernel() to read underlying + * integer storage. Macro functions as an expression and its return type is + * bpf_probe_read_kernel()'s return value: 0, on success, <0 on error. + */ +#define BPF_CORE_READ_BITFIELD_PROBED(s, field) ({ \ + unsigned long long val = 0; \ + \ + __CORE_BITFIELD_PROBE_READ(&val, s, field); \ + val <<= __CORE_RELO(s, field, LSHIFT_U64); \ + if (__CORE_RELO(s, field, SIGNED)) \ + val = ((long long)val) >> __CORE_RELO(s, field, RSHIFT_U64); \ + else \ + val = val >> __CORE_RELO(s, field, RSHIFT_U64); \ + val; \ +}) + +/* + * Extract bitfield, identified by s->field, and return its value as u64. + * This version of macro is using direct memory reads and should be used from + * BPF program types that support such functionality (e.g., typed raw + * tracepoints). + */ +#define BPF_CORE_READ_BITFIELD(s, field) ({ \ + const void *p = (const void *)s + __CORE_RELO(s, field, BYTE_OFFSET); \ + unsigned long long val; \ + \ + /* This is a so-called barrier_var() operation that makes specified \ + * variable "a black box" for optimizing compiler. \ + * It forces compiler to perform BYTE_OFFSET relocation on p and use \ + * its calculated value in the switch below, instead of applying \ + * the same relocation 4 times for each individual memory load. \ + */ \ + asm volatile("" : "=r"(p) : "0"(p)); \ + \ + switch (__CORE_RELO(s, field, BYTE_SIZE)) { \ + case 1: val = *(const unsigned char *)p; break; \ + case 2: val = *(const unsigned short *)p; break; \ + case 4: val = *(const unsigned int *)p; break; \ + case 8: val = *(const unsigned long long *)p; break; \ + default: val = 0; break; \ + } \ + val <<= __CORE_RELO(s, field, LSHIFT_U64); \ + if (__CORE_RELO(s, field, SIGNED)) \ + val = ((long long)val) >> __CORE_RELO(s, field, RSHIFT_U64); \ + else \ + val = val >> __CORE_RELO(s, field, RSHIFT_U64); \ + val; \ +}) + +/* + * Write to a bitfield, identified by s->field. + * This is the inverse of BPF_CORE_WRITE_BITFIELD(). + */ +#define BPF_CORE_WRITE_BITFIELD(s, field, new_val) ({ \ + void *p = (void *)s + __CORE_RELO(s, field, BYTE_OFFSET); \ + unsigned int byte_size = __CORE_RELO(s, field, BYTE_SIZE); \ + unsigned int lshift = __CORE_RELO(s, field, LSHIFT_U64); \ + unsigned int rshift = __CORE_RELO(s, field, RSHIFT_U64); \ + unsigned long long mask, val, nval = new_val; \ + unsigned int rpad = rshift - lshift; \ + \ + asm volatile("" : "+r"(p)); \ + \ + switch (byte_size) { \ + case 1: val = *(unsigned char *)p; break; \ + case 2: val = *(unsigned short *)p; break; \ + case 4: val = *(unsigned int *)p; break; \ + case 8: val = *(unsigned long long *)p; break; \ + } \ + \ + mask = (~0ULL << rshift) >> lshift; \ + val = (val & ~mask) | ((nval << rpad) & mask); \ + \ + switch (byte_size) { \ + case 1: *(unsigned char *)p = val; break; \ + case 2: *(unsigned short *)p = val; break; \ + case 4: *(unsigned int *)p = val; break; \ + case 8: *(unsigned long long *)p = val; break; \ + } \ +}) + +/* Differentiator between compilers builtin implementations. This is a + * requirement due to the compiler parsing differences where GCC optimizes + * early in parsing those constructs of type pointers to the builtin specific + * type, resulting in not being possible to collect the required type + * information in the builtin expansion. + */ +#ifdef __clang__ +#define ___bpf_typeof(type) ((typeof(type) *) 0) +#else +#define ___bpf_typeof1(type, NR) ({ \ + extern typeof(type) *___concat(bpf_type_tmp_, NR); \ + ___concat(bpf_type_tmp_, NR); \ +}) +#define ___bpf_typeof(type) ___bpf_typeof1(type, __COUNTER__) +#endif + +#ifdef __clang__ +#define ___bpf_field_ref1(field) (field) +#define ___bpf_field_ref2(type, field) (___bpf_typeof(type)->field) +#else +#define ___bpf_field_ref1(field) (&(field)) +#define ___bpf_field_ref2(type, field) (&(___bpf_typeof(type)->field)) +#endif +#define ___bpf_field_ref(args...) \ + ___bpf_apply(___bpf_field_ref, ___bpf_narg(args))(args) + +/* + * Convenience macro to check that field actually exists in target kernel's. + * Returns: + * 1, if matching field is present in target kernel; + * 0, if no matching field found. + * + * Supports two forms: + * - field reference through variable access: + * bpf_core_field_exists(p->my_field); + * - field reference through type and field names: + * bpf_core_field_exists(struct my_type, my_field). + */ +#define bpf_core_field_exists(field...) \ + __builtin_preserve_field_info(___bpf_field_ref(field), BPF_FIELD_EXISTS) + +/* + * Convenience macro to get the byte size of a field. Works for integers, + * struct/unions, pointers, arrays, and enums. + * + * Supports two forms: + * - field reference through variable access: + * bpf_core_field_size(p->my_field); + * - field reference through type and field names: + * bpf_core_field_size(struct my_type, my_field). + */ +#define bpf_core_field_size(field...) \ + __builtin_preserve_field_info(___bpf_field_ref(field), BPF_FIELD_BYTE_SIZE) + +/* + * Convenience macro to get field's byte offset. + * + * Supports two forms: + * - field reference through variable access: + * bpf_core_field_offset(p->my_field); + * - field reference through type and field names: + * bpf_core_field_offset(struct my_type, my_field). + */ +#define bpf_core_field_offset(field...) \ + __builtin_preserve_field_info(___bpf_field_ref(field), BPF_FIELD_BYTE_OFFSET) + +/* + * Convenience macro to get BTF type ID of a specified type, using a local BTF + * information. Return 32-bit unsigned integer with type ID from program's own + * BTF. Always succeeds. + */ +#define bpf_core_type_id_local(type) \ + __builtin_btf_type_id(*___bpf_typeof(type), BPF_TYPE_ID_LOCAL) + +/* + * Convenience macro to get BTF type ID of a target kernel's type that matches + * specified local type. + * Returns: + * - valid 32-bit unsigned type ID in kernel BTF; + * - 0, if no matching type was found in a target kernel BTF. + */ +#define bpf_core_type_id_kernel(type) \ + __builtin_btf_type_id(*___bpf_typeof(type), BPF_TYPE_ID_TARGET) + +/* + * Convenience macro to check that provided named type + * (struct/union/enum/typedef) exists in a target kernel. + * Returns: + * 1, if such type is present in target kernel's BTF; + * 0, if no matching type is found. + */ +#define bpf_core_type_exists(type) \ + __builtin_preserve_type_info(*___bpf_typeof(type), BPF_TYPE_EXISTS) + +/* + * Convenience macro to check that provided named type + * (struct/union/enum/typedef) "matches" that in a target kernel. + * Returns: + * 1, if the type matches in the target kernel's BTF; + * 0, if the type does not match any in the target kernel + */ +#define bpf_core_type_matches(type) \ + __builtin_preserve_type_info(*___bpf_typeof(type), BPF_TYPE_MATCHES) + +/* + * Convenience macro to get the byte size of a provided named type + * (struct/union/enum/typedef) in a target kernel. + * Returns: + * >= 0 size (in bytes), if type is present in target kernel's BTF; + * 0, if no matching type is found. + */ +#define bpf_core_type_size(type) \ + __builtin_preserve_type_info(*___bpf_typeof(type), BPF_TYPE_SIZE) + +/* + * Convenience macro to check that provided enumerator value is defined in + * a target kernel. + * Returns: + * 1, if specified enum type and its enumerator value are present in target + * kernel's BTF; + * 0, if no matching enum and/or enum value within that enum is found. + */ +#ifdef __clang__ +#define bpf_core_enum_value_exists(enum_type, enum_value) \ + __builtin_preserve_enum_value(*(typeof(enum_type) *)enum_value, BPF_ENUMVAL_EXISTS) +#else +#define bpf_core_enum_value_exists(enum_type, enum_value) \ + __builtin_preserve_enum_value(___bpf_typeof(enum_type), enum_value, BPF_ENUMVAL_EXISTS) +#endif + +/* + * Convenience macro to get the integer value of an enumerator value in + * a target kernel. + * Returns: + * 64-bit value, if specified enum type and its enumerator value are + * present in target kernel's BTF; + * 0, if no matching enum and/or enum value within that enum is found. + */ +#ifdef __clang__ +#define bpf_core_enum_value(enum_type, enum_value) \ + __builtin_preserve_enum_value(*(typeof(enum_type) *)enum_value, BPF_ENUMVAL_VALUE) +#else +#define bpf_core_enum_value(enum_type, enum_value) \ + __builtin_preserve_enum_value(___bpf_typeof(enum_type), enum_value, BPF_ENUMVAL_VALUE) +#endif + +/* + * bpf_core_read() abstracts away bpf_probe_read_kernel() call and captures + * offset relocation for source address using __builtin_preserve_access_index() + * built-in, provided by Clang. + * + * __builtin_preserve_access_index() takes as an argument an expression of + * taking an address of a field within struct/union. It makes compiler emit + * a relocation, which records BTF type ID describing root struct/union and an + * accessor string which describes exact embedded field that was used to take + * an address. See detailed description of this relocation format and + * semantics in comments to struct bpf_core_relo in include/uapi/linux/bpf.h. + * + * This relocation allows libbpf to adjust BPF instruction to use correct + * actual field offset, based on target kernel BTF type that matches original + * (local) BTF, used to record relocation. + */ +#define bpf_core_read(dst, sz, src) \ + bpf_probe_read_kernel(dst, sz, (const void *)__builtin_preserve_access_index(src)) + +/* NOTE: see comments for BPF_CORE_READ_USER() about the proper types use. */ +#define bpf_core_read_user(dst, sz, src) \ + bpf_probe_read_user(dst, sz, (const void *)__builtin_preserve_access_index(src)) +/* + * bpf_core_read_str() is a thin wrapper around bpf_probe_read_str() + * additionally emitting BPF CO-RE field relocation for specified source + * argument. + */ +#define bpf_core_read_str(dst, sz, src) \ + bpf_probe_read_kernel_str(dst, sz, (const void *)__builtin_preserve_access_index(src)) + +/* NOTE: see comments for BPF_CORE_READ_USER() about the proper types use. */ +#define bpf_core_read_user_str(dst, sz, src) \ + bpf_probe_read_user_str(dst, sz, (const void *)__builtin_preserve_access_index(src)) + +extern void *bpf_rdonly_cast(const void *obj, __u32 btf_id) __ksym __weak; + +/* + * Cast provided pointer *ptr* into a pointer to a specified *type* in such + * a way that BPF verifier will become aware of associated kernel-side BTF + * type. This allows to access members of kernel types directly without the + * need to use BPF_CORE_READ() macros. + */ +#define bpf_core_cast(ptr, type) \ + ((typeof(type) *)bpf_rdonly_cast((ptr), bpf_core_type_id_kernel(type))) + +#define ___concat(a, b) a ## b +#define ___apply(fn, n) ___concat(fn, n) +#define ___nth(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, __11, N, ...) N + +/* + * return number of provided arguments; used for switch-based variadic macro + * definitions (see ___last, ___arrow, etc below) + */ +#define ___narg(...) ___nth(_, ##__VA_ARGS__, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0) +/* + * return 0 if no arguments are passed, N - otherwise; used for + * recursively-defined macros to specify termination (0) case, and generic + * (N) case (e.g., ___read_ptrs, ___core_read) + */ +#define ___empty(...) ___nth(_, ##__VA_ARGS__, N, N, N, N, N, N, N, N, N, N, 0) + +#define ___last1(x) x +#define ___last2(a, x) x +#define ___last3(a, b, x) x +#define ___last4(a, b, c, x) x +#define ___last5(a, b, c, d, x) x +#define ___last6(a, b, c, d, e, x) x +#define ___last7(a, b, c, d, e, f, x) x +#define ___last8(a, b, c, d, e, f, g, x) x +#define ___last9(a, b, c, d, e, f, g, h, x) x +#define ___last10(a, b, c, d, e, f, g, h, i, x) x +#define ___last(...) ___apply(___last, ___narg(__VA_ARGS__))(__VA_ARGS__) + +#define ___nolast2(a, _) a +#define ___nolast3(a, b, _) a, b +#define ___nolast4(a, b, c, _) a, b, c +#define ___nolast5(a, b, c, d, _) a, b, c, d +#define ___nolast6(a, b, c, d, e, _) a, b, c, d, e +#define ___nolast7(a, b, c, d, e, f, _) a, b, c, d, e, f +#define ___nolast8(a, b, c, d, e, f, g, _) a, b, c, d, e, f, g +#define ___nolast9(a, b, c, d, e, f, g, h, _) a, b, c, d, e, f, g, h +#define ___nolast10(a, b, c, d, e, f, g, h, i, _) a, b, c, d, e, f, g, h, i +#define ___nolast(...) ___apply(___nolast, ___narg(__VA_ARGS__))(__VA_ARGS__) + +#define ___arrow1(a) a +#define ___arrow2(a, b) a->b +#define ___arrow3(a, b, c) a->b->c +#define ___arrow4(a, b, c, d) a->b->c->d +#define ___arrow5(a, b, c, d, e) a->b->c->d->e +#define ___arrow6(a, b, c, d, e, f) a->b->c->d->e->f +#define ___arrow7(a, b, c, d, e, f, g) a->b->c->d->e->f->g +#define ___arrow8(a, b, c, d, e, f, g, h) a->b->c->d->e->f->g->h +#define ___arrow9(a, b, c, d, e, f, g, h, i) a->b->c->d->e->f->g->h->i +#define ___arrow10(a, b, c, d, e, f, g, h, i, j) a->b->c->d->e->f->g->h->i->j +#define ___arrow(...) ___apply(___arrow, ___narg(__VA_ARGS__))(__VA_ARGS__) + +#define ___type(...) typeof(___arrow(__VA_ARGS__)) + +#define ___read(read_fn, dst, src_type, src, accessor) \ + read_fn((void *)(dst), sizeof(*(dst)), &((src_type)(src))->accessor) + +/* "recursively" read a sequence of inner pointers using local __t var */ +#define ___rd_first(fn, src, a) ___read(fn, &__t, ___type(src), src, a); +#define ___rd_last(fn, ...) \ + ___read(fn, &__t, ___type(___nolast(__VA_ARGS__)), __t, ___last(__VA_ARGS__)); +#define ___rd_p1(fn, ...) const void *__t; ___rd_first(fn, __VA_ARGS__) +#define ___rd_p2(fn, ...) ___rd_p1(fn, ___nolast(__VA_ARGS__)) ___rd_last(fn, __VA_ARGS__) +#define ___rd_p3(fn, ...) ___rd_p2(fn, ___nolast(__VA_ARGS__)) ___rd_last(fn, __VA_ARGS__) +#define ___rd_p4(fn, ...) ___rd_p3(fn, ___nolast(__VA_ARGS__)) ___rd_last(fn, __VA_ARGS__) +#define ___rd_p5(fn, ...) ___rd_p4(fn, ___nolast(__VA_ARGS__)) ___rd_last(fn, __VA_ARGS__) +#define ___rd_p6(fn, ...) ___rd_p5(fn, ___nolast(__VA_ARGS__)) ___rd_last(fn, __VA_ARGS__) +#define ___rd_p7(fn, ...) ___rd_p6(fn, ___nolast(__VA_ARGS__)) ___rd_last(fn, __VA_ARGS__) +#define ___rd_p8(fn, ...) ___rd_p7(fn, ___nolast(__VA_ARGS__)) ___rd_last(fn, __VA_ARGS__) +#define ___rd_p9(fn, ...) ___rd_p8(fn, ___nolast(__VA_ARGS__)) ___rd_last(fn, __VA_ARGS__) +#define ___read_ptrs(fn, src, ...) \ + ___apply(___rd_p, ___narg(__VA_ARGS__))(fn, src, __VA_ARGS__) + +#define ___core_read0(fn, fn_ptr, dst, src, a) \ + ___read(fn, dst, ___type(src), src, a); +#define ___core_readN(fn, fn_ptr, dst, src, ...) \ + ___read_ptrs(fn_ptr, src, ___nolast(__VA_ARGS__)) \ + ___read(fn, dst, ___type(src, ___nolast(__VA_ARGS__)), __t, \ + ___last(__VA_ARGS__)); +#define ___core_read(fn, fn_ptr, dst, src, a, ...) \ + ___apply(___core_read, ___empty(__VA_ARGS__))(fn, fn_ptr, dst, \ + src, a, ##__VA_ARGS__) + +/* + * BPF_CORE_READ_INTO() is a more performance-conscious variant of + * BPF_CORE_READ(), in which final field is read into user-provided storage. + * See BPF_CORE_READ() below for more details on general usage. + */ +#define BPF_CORE_READ_INTO(dst, src, a, ...) ({ \ + ___core_read(bpf_core_read, bpf_core_read, \ + dst, (src), a, ##__VA_ARGS__) \ +}) + +/* + * Variant of BPF_CORE_READ_INTO() for reading from user-space memory. + * + * NOTE: see comments for BPF_CORE_READ_USER() about the proper types use. + */ +#define BPF_CORE_READ_USER_INTO(dst, src, a, ...) ({ \ + ___core_read(bpf_core_read_user, bpf_core_read_user, \ + dst, (src), a, ##__VA_ARGS__) \ +}) + +/* Non-CO-RE variant of BPF_CORE_READ_INTO() */ +#define BPF_PROBE_READ_INTO(dst, src, a, ...) ({ \ + ___core_read(bpf_probe_read_kernel, bpf_probe_read_kernel, \ + dst, (src), a, ##__VA_ARGS__) \ +}) + +/* Non-CO-RE variant of BPF_CORE_READ_USER_INTO(). + * + * As no CO-RE relocations are emitted, source types can be arbitrary and are + * not restricted to kernel types only. + */ +#define BPF_PROBE_READ_USER_INTO(dst, src, a, ...) ({ \ + ___core_read(bpf_probe_read_user, bpf_probe_read_user, \ + dst, (src), a, ##__VA_ARGS__) \ +}) + +/* + * BPF_CORE_READ_STR_INTO() does same "pointer chasing" as + * BPF_CORE_READ() for intermediate pointers, but then executes (and returns + * corresponding error code) bpf_core_read_str() for final string read. + */ +#define BPF_CORE_READ_STR_INTO(dst, src, a, ...) ({ \ + ___core_read(bpf_core_read_str, bpf_core_read, \ + dst, (src), a, ##__VA_ARGS__) \ +}) + +/* + * Variant of BPF_CORE_READ_STR_INTO() for reading from user-space memory. + * + * NOTE: see comments for BPF_CORE_READ_USER() about the proper types use. + */ +#define BPF_CORE_READ_USER_STR_INTO(dst, src, a, ...) ({ \ + ___core_read(bpf_core_read_user_str, bpf_core_read_user, \ + dst, (src), a, ##__VA_ARGS__) \ +}) + +/* Non-CO-RE variant of BPF_CORE_READ_STR_INTO() */ +#define BPF_PROBE_READ_STR_INTO(dst, src, a, ...) ({ \ + ___core_read(bpf_probe_read_kernel_str, bpf_probe_read_kernel, \ + dst, (src), a, ##__VA_ARGS__) \ +}) + +/* + * Non-CO-RE variant of BPF_CORE_READ_USER_STR_INTO(). + * + * As no CO-RE relocations are emitted, source types can be arbitrary and are + * not restricted to kernel types only. + */ +#define BPF_PROBE_READ_USER_STR_INTO(dst, src, a, ...) ({ \ + ___core_read(bpf_probe_read_user_str, bpf_probe_read_user, \ + dst, (src), a, ##__VA_ARGS__) \ +}) + +/* + * BPF_CORE_READ() is used to simplify BPF CO-RE relocatable read, especially + * when there are few pointer chasing steps. + * E.g., what in non-BPF world (or in BPF w/ BCC) would be something like: + * int x = s->a.b.c->d.e->f->g; + * can be succinctly achieved using BPF_CORE_READ as: + * int x = BPF_CORE_READ(s, a.b.c, d.e, f, g); + * + * BPF_CORE_READ will decompose above statement into 4 bpf_core_read (BPF + * CO-RE relocatable bpf_probe_read_kernel() wrapper) calls, logically + * equivalent to: + * 1. const void *__t = s->a.b.c; + * 2. __t = __t->d.e; + * 3. __t = __t->f; + * 4. return __t->g; + * + * Equivalence is logical, because there is a heavy type casting/preservation + * involved, as well as all the reads are happening through + * bpf_probe_read_kernel() calls using __builtin_preserve_access_index() to + * emit CO-RE relocations. + * + * N.B. Only up to 9 "field accessors" are supported, which should be more + * than enough for any practical purpose. + */ +#define BPF_CORE_READ(src, a, ...) ({ \ + ___type((src), a, ##__VA_ARGS__) __r; \ + BPF_CORE_READ_INTO(&__r, (src), a, ##__VA_ARGS__); \ + __r; \ +}) + +/* + * Variant of BPF_CORE_READ() for reading from user-space memory. + * + * NOTE: all the source types involved are still *kernel types* and need to + * exist in kernel (or kernel module) BTF, otherwise CO-RE relocation will + * fail. Custom user types are not relocatable with CO-RE. + * The typical situation in which BPF_CORE_READ_USER() might be used is to + * read kernel UAPI types from the user-space memory passed in as a syscall + * input argument. + */ +#define BPF_CORE_READ_USER(src, a, ...) ({ \ + ___type((src), a, ##__VA_ARGS__) __r; \ + BPF_CORE_READ_USER_INTO(&__r, (src), a, ##__VA_ARGS__); \ + __r; \ +}) + +/* Non-CO-RE variant of BPF_CORE_READ() */ +#define BPF_PROBE_READ(src, a, ...) ({ \ + ___type((src), a, ##__VA_ARGS__) __r; \ + BPF_PROBE_READ_INTO(&__r, (src), a, ##__VA_ARGS__); \ + __r; \ +}) + +/* + * Non-CO-RE variant of BPF_CORE_READ_USER(). + * + * As no CO-RE relocations are emitted, source types can be arbitrary and are + * not restricted to kernel types only. + */ +#define BPF_PROBE_READ_USER(src, a, ...) ({ \ + ___type((src), a, ##__VA_ARGS__) __r; \ + BPF_PROBE_READ_USER_INTO(&__r, (src), a, ##__VA_ARGS__); \ + __r; \ +}) + +#endif + diff --git a/internal/ebpf/spike/c/bpf_endian.h b/internal/ebpf/spike/c/bpf_endian.h new file mode 100644 index 000000000..ec9db4fec --- /dev/null +++ b/internal/ebpf/spike/c/bpf_endian.h @@ -0,0 +1,99 @@ +/* SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause) */ +#ifndef __BPF_ENDIAN__ +#define __BPF_ENDIAN__ + +/* + * Isolate byte #n and put it into byte #m, for __u##b type. + * E.g., moving byte #6 (nnnnnnnn) into byte #1 (mmmmmmmm) for __u64: + * 1) xxxxxxxx nnnnnnnn xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx mmmmmmmm xxxxxxxx + * 2) nnnnnnnn xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx mmmmmmmm xxxxxxxx 00000000 + * 3) 00000000 00000000 00000000 00000000 00000000 00000000 00000000 nnnnnnnn + * 4) 00000000 00000000 00000000 00000000 00000000 00000000 nnnnnnnn 00000000 + */ +#define ___bpf_mvb(x, b, n, m) ((__u##b)(x) << (b-(n+1)*8) >> (b-8) << (m*8)) + +#define ___bpf_swab16(x) ((__u16)( \ + ___bpf_mvb(x, 16, 0, 1) | \ + ___bpf_mvb(x, 16, 1, 0))) + +#define ___bpf_swab32(x) ((__u32)( \ + ___bpf_mvb(x, 32, 0, 3) | \ + ___bpf_mvb(x, 32, 1, 2) | \ + ___bpf_mvb(x, 32, 2, 1) | \ + ___bpf_mvb(x, 32, 3, 0))) + +#define ___bpf_swab64(x) ((__u64)( \ + ___bpf_mvb(x, 64, 0, 7) | \ + ___bpf_mvb(x, 64, 1, 6) | \ + ___bpf_mvb(x, 64, 2, 5) | \ + ___bpf_mvb(x, 64, 3, 4) | \ + ___bpf_mvb(x, 64, 4, 3) | \ + ___bpf_mvb(x, 64, 5, 2) | \ + ___bpf_mvb(x, 64, 6, 1) | \ + ___bpf_mvb(x, 64, 7, 0))) + +/* LLVM's BPF target selects the endianness of the CPU + * it compiles on, or the user specifies (bpfel/bpfeb), + * respectively. The used __BYTE_ORDER__ is defined by + * the compiler, we cannot rely on __BYTE_ORDER from + * libc headers, since it doesn't reflect the actual + * requested byte order. + * + * Note, LLVM's BPF target has different __builtin_bswapX() + * semantics. It does map to BPF_ALU | BPF_END | BPF_TO_BE + * in bpfel and bpfeb case, which means below, that we map + * to cpu_to_be16(). We could use it unconditionally in BPF + * case, but better not rely on it, so that this header here + * can be used from application and BPF program side, which + * use different targets. + */ +#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ +# define __bpf_ntohs(x) __builtin_bswap16(x) +# define __bpf_htons(x) __builtin_bswap16(x) +# define __bpf_constant_ntohs(x) ___bpf_swab16(x) +# define __bpf_constant_htons(x) ___bpf_swab16(x) +# define __bpf_ntohl(x) __builtin_bswap32(x) +# define __bpf_htonl(x) __builtin_bswap32(x) +# define __bpf_constant_ntohl(x) ___bpf_swab32(x) +# define __bpf_constant_htonl(x) ___bpf_swab32(x) +# define __bpf_be64_to_cpu(x) __builtin_bswap64(x) +# define __bpf_cpu_to_be64(x) __builtin_bswap64(x) +# define __bpf_constant_be64_to_cpu(x) ___bpf_swab64(x) +# define __bpf_constant_cpu_to_be64(x) ___bpf_swab64(x) +#elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ +# define __bpf_ntohs(x) (x) +# define __bpf_htons(x) (x) +# define __bpf_constant_ntohs(x) (x) +# define __bpf_constant_htons(x) (x) +# define __bpf_ntohl(x) (x) +# define __bpf_htonl(x) (x) +# define __bpf_constant_ntohl(x) (x) +# define __bpf_constant_htonl(x) (x) +# define __bpf_be64_to_cpu(x) (x) +# define __bpf_cpu_to_be64(x) (x) +# define __bpf_constant_be64_to_cpu(x) (x) +# define __bpf_constant_cpu_to_be64(x) (x) +#else +# error "Fix your compiler's __BYTE_ORDER__?!" +#endif + +#define bpf_htons(x) \ + (__builtin_constant_p(x) ? \ + __bpf_constant_htons(x) : __bpf_htons(x)) +#define bpf_ntohs(x) \ + (__builtin_constant_p(x) ? \ + __bpf_constant_ntohs(x) : __bpf_ntohs(x)) +#define bpf_htonl(x) \ + (__builtin_constant_p(x) ? \ + __bpf_constant_htonl(x) : __bpf_htonl(x)) +#define bpf_ntohl(x) \ + (__builtin_constant_p(x) ? \ + __bpf_constant_ntohl(x) : __bpf_ntohl(x)) +#define bpf_cpu_to_be64(x) \ + (__builtin_constant_p(x) ? \ + __bpf_constant_cpu_to_be64(x) : __bpf_cpu_to_be64(x)) +#define bpf_be64_to_cpu(x) \ + (__builtin_constant_p(x) ? \ + __bpf_constant_be64_to_cpu(x) : __bpf_be64_to_cpu(x)) + +#endif /* __BPF_ENDIAN__ */ diff --git a/internal/ebpf/spike/c/bpf_helper_defs.h b/internal/ebpf/spike/c/bpf_helper_defs.h new file mode 100644 index 000000000..3fbe7ff2a --- /dev/null +++ b/internal/ebpf/spike/c/bpf_helper_defs.h @@ -0,0 +1,4139 @@ +/* This is auto-generated file. See bpf_doc.py for details. */ + +/* Forward declarations of BPF structs */ +struct bpf_fib_lookup; +struct bpf_sk_lookup; +struct bpf_perf_event_data; +struct bpf_perf_event_value; +struct bpf_pidns_info; +struct bpf_redir_neigh; +struct bpf_sock; +struct bpf_sock_addr; +struct bpf_sock_ops; +struct bpf_sock_tuple; +struct bpf_spin_lock; +struct bpf_sysctl; +struct bpf_tcp_sock; +struct bpf_tunnel_key; +struct bpf_xfrm_state; +struct linux_binprm; +struct pt_regs; +struct sk_reuseport_md; +struct sockaddr; +struct tcphdr; +struct seq_file; +struct tcp6_sock; +struct tcp_sock; +struct tcp_timewait_sock; +struct tcp_request_sock; +struct udp6_sock; +struct unix_sock; +struct task_struct; +struct __sk_buff; +struct sk_msg_md; +struct xdp_md; +struct path; +struct btf_ptr; +struct inode; +struct socket; +struct file; +struct bpf_timer; + +/* + * bpf_map_lookup_elem + * + * Perform a lookup in *map* for an entry associated to *key*. + * + * Returns + * Map value associated to *key*, or **NULL** if no entry was + * found. + */ +static void *(*bpf_map_lookup_elem)(void *map, const void *key) = (void *) 1; + +/* + * bpf_map_update_elem + * + * Add or update the value of the entry associated to *key* in + * *map* with *value*. *flags* is one of: + * + * **BPF_NOEXIST** + * The entry for *key* must not exist in the map. + * **BPF_EXIST** + * The entry for *key* must already exist in the map. + * **BPF_ANY** + * No condition on the existence of the entry for *key*. + * + * Flag value **BPF_NOEXIST** cannot be used for maps of types + * **BPF_MAP_TYPE_ARRAY** or **BPF_MAP_TYPE_PERCPU_ARRAY** (all + * elements always exist), the helper would return an error. + * + * Returns + * 0 on success, or a negative error in case of failure. + */ +static long (*bpf_map_update_elem)(void *map, const void *key, const void *value, __u64 flags) = (void *) 2; + +/* + * bpf_map_delete_elem + * + * Delete entry with *key* from *map*. + * + * Returns + * 0 on success, or a negative error in case of failure. + */ +static long (*bpf_map_delete_elem)(void *map, const void *key) = (void *) 3; + +/* + * bpf_probe_read + * + * For tracing programs, safely attempt to read *size* bytes from + * kernel space address *unsafe_ptr* and store the data in *dst*. + * + * Generally, use **bpf_probe_read_user**\ () or + * **bpf_probe_read_kernel**\ () instead. + * + * Returns + * 0 on success, or a negative error in case of failure. + */ +static long (*bpf_probe_read)(void *dst, __u32 size, const void *unsafe_ptr) = (void *) 4; + +/* + * bpf_ktime_get_ns + * + * Return the time elapsed since system boot, in nanoseconds. + * Does not include time the system was suspended. + * See: **clock_gettime**\ (**CLOCK_MONOTONIC**) + * + * Returns + * Current *ktime*. + */ +static __u64 (*bpf_ktime_get_ns)(void) = (void *) 5; + +/* + * bpf_trace_printk + * + * This helper is a "printk()-like" facility for debugging. It + * prints a message defined by format *fmt* (of size *fmt_size*) + * to file *\/sys/kernel/debug/tracing/trace* from DebugFS, if + * available. It can take up to three additional **u64** + * arguments (as an eBPF helpers, the total number of arguments is + * limited to five). + * + * Each time the helper is called, it appends a line to the trace. + * Lines are discarded while *\/sys/kernel/debug/tracing/trace* is + * open, use *\/sys/kernel/debug/tracing/trace_pipe* to avoid this. + * The format of the trace is customizable, and the exact output + * one will get depends on the options set in + * *\/sys/kernel/debug/tracing/trace_options* (see also the + * *README* file under the same directory). However, it usually + * defaults to something like: + * + * :: + * + * telnet-470 [001] .N.. 419421.045894: 0x00000001: + * + * In the above: + * + * * ``telnet`` is the name of the current task. + * * ``470`` is the PID of the current task. + * * ``001`` is the CPU number on which the task is + * running. + * * In ``.N..``, each character refers to a set of + * options (whether irqs are enabled, scheduling + * options, whether hard/softirqs are running, level of + * preempt_disabled respectively). **N** means that + * **TIF_NEED_RESCHED** and **PREEMPT_NEED_RESCHED** + * are set. + * * ``419421.045894`` is a timestamp. + * * ``0x00000001`` is a fake value used by BPF for the + * instruction pointer register. + * * ```` is the message formatted with + * *fmt*. + * + * The conversion specifiers supported by *fmt* are similar, but + * more limited than for printk(). They are **%d**, **%i**, + * **%u**, **%x**, **%ld**, **%li**, **%lu**, **%lx**, **%lld**, + * **%lli**, **%llu**, **%llx**, **%p**, **%s**. No modifier (size + * of field, padding with zeroes, etc.) is available, and the + * helper will return **-EINVAL** (but print nothing) if it + * encounters an unknown specifier. + * + * Also, note that **bpf_trace_printk**\ () is slow, and should + * only be used for debugging purposes. For this reason, a notice + * block (spanning several lines) is printed to kernel logs and + * states that the helper should not be used "for production use" + * the first time this helper is used (or more precisely, when + * **trace_printk**\ () buffers are allocated). For passing values + * to user space, perf events should be preferred. + * + * Returns + * The number of bytes written to the buffer, or a negative error + * in case of failure. + */ +static long (*bpf_trace_printk)(const char *fmt, __u32 fmt_size, ...) = (void *) 6; + +/* + * bpf_get_prandom_u32 + * + * Get a pseudo-random number. + * + * From a security point of view, this helper uses its own + * pseudo-random internal state, and cannot be used to infer the + * seed of other random functions in the kernel. However, it is + * essential to note that the generator used by the helper is not + * cryptographically secure. + * + * Returns + * A random 32-bit unsigned value. + */ +static __u32 (*bpf_get_prandom_u32)(void) = (void *) 7; + +/* + * bpf_get_smp_processor_id + * + * Get the SMP (symmetric multiprocessing) processor id. Note that + * all programs run with migration disabled, which means that the + * SMP processor id is stable during all the execution of the + * program. + * + * Returns + * The SMP id of the processor running the program. + */ +static __u32 (*bpf_get_smp_processor_id)(void) = (void *) 8; + +/* + * bpf_skb_store_bytes + * + * Store *len* bytes from address *from* into the packet + * associated to *skb*, at *offset*. *flags* are a combination of + * **BPF_F_RECOMPUTE_CSUM** (automatically recompute the + * checksum for the packet after storing the bytes) and + * **BPF_F_INVALIDATE_HASH** (set *skb*\ **->hash**, *skb*\ + * **->swhash** and *skb*\ **->l4hash** to 0). + * + * A call to this helper is susceptible to change the underlying + * packet buffer. Therefore, at load time, all checks on pointers + * previously done by the verifier are invalidated and must be + * performed again, if the helper is used in combination with + * direct packet access. + * + * Returns + * 0 on success, or a negative error in case of failure. + */ +static long (*bpf_skb_store_bytes)(struct __sk_buff *skb, __u32 offset, const void *from, __u32 len, __u64 flags) = (void *) 9; + +/* + * bpf_l3_csum_replace + * + * Recompute the layer 3 (e.g. IP) checksum for the packet + * associated to *skb*. Computation is incremental, so the helper + * must know the former value of the header field that was + * modified (*from*), the new value of this field (*to*), and the + * number of bytes (2 or 4) for this field, stored in *size*. + * Alternatively, it is possible to store the difference between + * the previous and the new values of the header field in *to*, by + * setting *from* and *size* to 0. For both methods, *offset* + * indicates the location of the IP checksum within the packet. + * + * This helper works in combination with **bpf_csum_diff**\ (), + * which does not update the checksum in-place, but offers more + * flexibility and can handle sizes larger than 2 or 4 for the + * checksum to update. + * + * A call to this helper is susceptible to change the underlying + * packet buffer. Therefore, at load time, all checks on pointers + * previously done by the verifier are invalidated and must be + * performed again, if the helper is used in combination with + * direct packet access. + * + * Returns + * 0 on success, or a negative error in case of failure. + */ +static long (*bpf_l3_csum_replace)(struct __sk_buff *skb, __u32 offset, __u64 from, __u64 to, __u64 size) = (void *) 10; + +/* + * bpf_l4_csum_replace + * + * Recompute the layer 4 (e.g. TCP, UDP or ICMP) checksum for the + * packet associated to *skb*. Computation is incremental, so the + * helper must know the former value of the header field that was + * modified (*from*), the new value of this field (*to*), and the + * number of bytes (2 or 4) for this field, stored on the lowest + * four bits of *flags*. Alternatively, it is possible to store + * the difference between the previous and the new values of the + * header field in *to*, by setting *from* and the four lowest + * bits of *flags* to 0. For both methods, *offset* indicates the + * location of the IP checksum within the packet. In addition to + * the size of the field, *flags* can be added (bitwise OR) actual + * flags. With **BPF_F_MARK_MANGLED_0**, a null checksum is left + * untouched (unless **BPF_F_MARK_ENFORCE** is added as well), and + * for updates resulting in a null checksum the value is set to + * **CSUM_MANGLED_0** instead. Flag **BPF_F_PSEUDO_HDR** indicates + * the checksum is to be computed against a pseudo-header. + * + * This helper works in combination with **bpf_csum_diff**\ (), + * which does not update the checksum in-place, but offers more + * flexibility and can handle sizes larger than 2 or 4 for the + * checksum to update. + * + * A call to this helper is susceptible to change the underlying + * packet buffer. Therefore, at load time, all checks on pointers + * previously done by the verifier are invalidated and must be + * performed again, if the helper is used in combination with + * direct packet access. + * + * Returns + * 0 on success, or a negative error in case of failure. + */ +static long (*bpf_l4_csum_replace)(struct __sk_buff *skb, __u32 offset, __u64 from, __u64 to, __u64 flags) = (void *) 11; + +/* + * bpf_tail_call + * + * This special helper is used to trigger a "tail call", or in + * other words, to jump into another eBPF program. The same stack + * frame is used (but values on stack and in registers for the + * caller are not accessible to the callee). This mechanism allows + * for program chaining, either for raising the maximum number of + * available eBPF instructions, or to execute given programs in + * conditional blocks. For security reasons, there is an upper + * limit to the number of successive tail calls that can be + * performed. + * + * Upon call of this helper, the program attempts to jump into a + * program referenced at index *index* in *prog_array_map*, a + * special map of type **BPF_MAP_TYPE_PROG_ARRAY**, and passes + * *ctx*, a pointer to the context. + * + * If the call succeeds, the kernel immediately runs the first + * instruction of the new program. This is not a function call, + * and it never returns to the previous program. If the call + * fails, then the helper has no effect, and the caller continues + * to run its subsequent instructions. A call can fail if the + * destination program for the jump does not exist (i.e. *index* + * is superior to the number of entries in *prog_array_map*), or + * if the maximum number of tail calls has been reached for this + * chain of programs. This limit is defined in the kernel by the + * macro **MAX_TAIL_CALL_CNT** (not accessible to user space), + * which is currently set to 33. + * + * Returns + * 0 on success, or a negative error in case of failure. + */ +static long (*bpf_tail_call)(void *ctx, void *prog_array_map, __u32 index) = (void *) 12; + +/* + * bpf_clone_redirect + * + * Clone and redirect the packet associated to *skb* to another + * net device of index *ifindex*. Both ingress and egress + * interfaces can be used for redirection. The **BPF_F_INGRESS** + * value in *flags* is used to make the distinction (ingress path + * is selected if the flag is present, egress path otherwise). + * This is the only flag supported for now. + * + * In comparison with **bpf_redirect**\ () helper, + * **bpf_clone_redirect**\ () has the associated cost of + * duplicating the packet buffer, but this can be executed out of + * the eBPF program. Conversely, **bpf_redirect**\ () is more + * efficient, but it is handled through an action code where the + * redirection happens only after the eBPF program has returned. + * + * A call to this helper is susceptible to change the underlying + * packet buffer. Therefore, at load time, all checks on pointers + * previously done by the verifier are invalidated and must be + * performed again, if the helper is used in combination with + * direct packet access. + * + * Returns + * 0 on success, or a negative error in case of failure. + */ +static long (*bpf_clone_redirect)(struct __sk_buff *skb, __u32 ifindex, __u64 flags) = (void *) 13; + +/* + * bpf_get_current_pid_tgid + * + * + * Returns + * A 64-bit integer containing the current tgid and pid, and + * created as such: + * *current_task*\ **->tgid << 32 \|** + * *current_task*\ **->pid**. + */ +static __u64 (*bpf_get_current_pid_tgid)(void) = (void *) 14; + +/* + * bpf_get_current_uid_gid + * + * + * Returns + * A 64-bit integer containing the current GID and UID, and + * created as such: *current_gid* **<< 32 \|** *current_uid*. + */ +static __u64 (*bpf_get_current_uid_gid)(void) = (void *) 15; + +/* + * bpf_get_current_comm + * + * Copy the **comm** attribute of the current task into *buf* of + * *size_of_buf*. The **comm** attribute contains the name of + * the executable (excluding the path) for the current task. The + * *size_of_buf* must be strictly positive. On success, the + * helper makes sure that the *buf* is NUL-terminated. On failure, + * it is filled with zeroes. + * + * Returns + * 0 on success, or a negative error in case of failure. + */ +static long (*bpf_get_current_comm)(void *buf, __u32 size_of_buf) = (void *) 16; + +/* + * bpf_get_cgroup_classid + * + * Retrieve the classid for the current task, i.e. for the net_cls + * cgroup to which *skb* belongs. + * + * This helper can be used on TC egress path, but not on ingress. + * + * The net_cls cgroup provides an interface to tag network packets + * based on a user-provided identifier for all traffic coming from + * the tasks belonging to the related cgroup. See also the related + * kernel documentation, available from the Linux sources in file + * *Documentation/admin-guide/cgroup-v1/net_cls.rst*. + * + * The Linux kernel has two versions for cgroups: there are + * cgroups v1 and cgroups v2. Both are available to users, who can + * use a mixture of them, but note that the net_cls cgroup is for + * cgroup v1 only. This makes it incompatible with BPF programs + * run on cgroups, which is a cgroup-v2-only feature (a socket can + * only hold data for one version of cgroups at a time). + * + * This helper is only available is the kernel was compiled with + * the **CONFIG_CGROUP_NET_CLASSID** configuration option set to + * "**y**" or to "**m**". + * + * Returns + * The classid, or 0 for the default unconfigured classid. + */ +static __u32 (*bpf_get_cgroup_classid)(struct __sk_buff *skb) = (void *) 17; + +/* + * bpf_skb_vlan_push + * + * Push a *vlan_tci* (VLAN tag control information) of protocol + * *vlan_proto* to the packet associated to *skb*, then update + * the checksum. Note that if *vlan_proto* is different from + * **ETH_P_8021Q** and **ETH_P_8021AD**, it is considered to + * be **ETH_P_8021Q**. + * + * A call to this helper is susceptible to change the underlying + * packet buffer. Therefore, at load time, all checks on pointers + * previously done by the verifier are invalidated and must be + * performed again, if the helper is used in combination with + * direct packet access. + * + * Returns + * 0 on success, or a negative error in case of failure. + */ +static long (*bpf_skb_vlan_push)(struct __sk_buff *skb, __be16 vlan_proto, __u16 vlan_tci) = (void *) 18; + +/* + * bpf_skb_vlan_pop + * + * Pop a VLAN header from the packet associated to *skb*. + * + * A call to this helper is susceptible to change the underlying + * packet buffer. Therefore, at load time, all checks on pointers + * previously done by the verifier are invalidated and must be + * performed again, if the helper is used in combination with + * direct packet access. + * + * Returns + * 0 on success, or a negative error in case of failure. + */ +static long (*bpf_skb_vlan_pop)(struct __sk_buff *skb) = (void *) 19; + +/* + * bpf_skb_get_tunnel_key + * + * Get tunnel metadata. This helper takes a pointer *key* to an + * empty **struct bpf_tunnel_key** of **size**, that will be + * filled with tunnel metadata for the packet associated to *skb*. + * The *flags* can be set to **BPF_F_TUNINFO_IPV6**, which + * indicates that the tunnel is based on IPv6 protocol instead of + * IPv4. + * + * The **struct bpf_tunnel_key** is an object that generalizes the + * principal parameters used by various tunneling protocols into a + * single struct. This way, it can be used to easily make a + * decision based on the contents of the encapsulation header, + * "summarized" in this struct. In particular, it holds the IP + * address of the remote end (IPv4 or IPv6, depending on the case) + * in *key*\ **->remote_ipv4** or *key*\ **->remote_ipv6**. Also, + * this struct exposes the *key*\ **->tunnel_id**, which is + * generally mapped to a VNI (Virtual Network Identifier), making + * it programmable together with the **bpf_skb_set_tunnel_key**\ + * () helper. + * + * Let's imagine that the following code is part of a program + * attached to the TC ingress interface, on one end of a GRE + * tunnel, and is supposed to filter out all messages coming from + * remote ends with IPv4 address other than 10.0.0.1: + * + * :: + * + * int ret; + * struct bpf_tunnel_key key = {}; + * + * ret = bpf_skb_get_tunnel_key(skb, &key, sizeof(key), 0); + * if (ret < 0) + * return TC_ACT_SHOT; // drop packet + * + * if (key.remote_ipv4 != 0x0a000001) + * return TC_ACT_SHOT; // drop packet + * + * return TC_ACT_OK; // accept packet + * + * This interface can also be used with all encapsulation devices + * that can operate in "collect metadata" mode: instead of having + * one network device per specific configuration, the "collect + * metadata" mode only requires a single device where the + * configuration can be extracted from this helper. + * + * This can be used together with various tunnels such as VXLan, + * Geneve, GRE or IP in IP (IPIP). + * + * Returns + * 0 on success, or a negative error in case of failure. + */ +static long (*bpf_skb_get_tunnel_key)(struct __sk_buff *skb, struct bpf_tunnel_key *key, __u32 size, __u64 flags) = (void *) 20; + +/* + * bpf_skb_set_tunnel_key + * + * Populate tunnel metadata for packet associated to *skb.* The + * tunnel metadata is set to the contents of *key*, of *size*. The + * *flags* can be set to a combination of the following values: + * + * **BPF_F_TUNINFO_IPV6** + * Indicate that the tunnel is based on IPv6 protocol + * instead of IPv4. + * **BPF_F_ZERO_CSUM_TX** + * For IPv4 packets, add a flag to tunnel metadata + * indicating that checksum computation should be skipped + * and checksum set to zeroes. + * **BPF_F_DONT_FRAGMENT** + * Add a flag to tunnel metadata indicating that the + * packet should not be fragmented. + * **BPF_F_SEQ_NUMBER** + * Add a flag to tunnel metadata indicating that a + * sequence number should be added to tunnel header before + * sending the packet. This flag was added for GRE + * encapsulation, but might be used with other protocols + * as well in the future. + * + * Here is a typical usage on the transmit path: + * + * :: + * + * struct bpf_tunnel_key key; + * populate key ... + * bpf_skb_set_tunnel_key(skb, &key, sizeof(key), 0); + * bpf_clone_redirect(skb, vxlan_dev_ifindex, 0); + * + * See also the description of the **bpf_skb_get_tunnel_key**\ () + * helper for additional information. + * + * Returns + * 0 on success, or a negative error in case of failure. + */ +static long (*bpf_skb_set_tunnel_key)(struct __sk_buff *skb, struct bpf_tunnel_key *key, __u32 size, __u64 flags) = (void *) 21; + +/* + * bpf_perf_event_read + * + * Read the value of a perf event counter. This helper relies on a + * *map* of type **BPF_MAP_TYPE_PERF_EVENT_ARRAY**. The nature of + * the perf event counter is selected when *map* is updated with + * perf event file descriptors. The *map* is an array whose size + * is the number of available CPUs, and each cell contains a value + * relative to one CPU. The value to retrieve is indicated by + * *flags*, that contains the index of the CPU to look up, masked + * with **BPF_F_INDEX_MASK**. Alternatively, *flags* can be set to + * **BPF_F_CURRENT_CPU** to indicate that the value for the + * current CPU should be retrieved. + * + * Note that before Linux 4.13, only hardware perf event can be + * retrieved. + * + * Also, be aware that the newer helper + * **bpf_perf_event_read_value**\ () is recommended over + * **bpf_perf_event_read**\ () in general. The latter has some ABI + * quirks where error and counter value are used as a return code + * (which is wrong to do since ranges may overlap). This issue is + * fixed with **bpf_perf_event_read_value**\ (), which at the same + * time provides more features over the **bpf_perf_event_read**\ + * () interface. Please refer to the description of + * **bpf_perf_event_read_value**\ () for details. + * + * Returns + * The value of the perf event counter read from the map, or a + * negative error code in case of failure. + */ +static __u64 (*bpf_perf_event_read)(void *map, __u64 flags) = (void *) 22; + +/* + * bpf_redirect + * + * Redirect the packet to another net device of index *ifindex*. + * This helper is somewhat similar to **bpf_clone_redirect**\ + * (), except that the packet is not cloned, which provides + * increased performance. + * + * Except for XDP, both ingress and egress interfaces can be used + * for redirection. The **BPF_F_INGRESS** value in *flags* is used + * to make the distinction (ingress path is selected if the flag + * is present, egress path otherwise). Currently, XDP only + * supports redirection to the egress interface, and accepts no + * flag at all. + * + * The same effect can also be attained with the more generic + * **bpf_redirect_map**\ (), which uses a BPF map to store the + * redirect target instead of providing it directly to the helper. + * + * Returns + * For XDP, the helper returns **XDP_REDIRECT** on success or + * **XDP_ABORTED** on error. For other program types, the values + * are **TC_ACT_REDIRECT** on success or **TC_ACT_SHOT** on + * error. + */ +static long (*bpf_redirect)(__u32 ifindex, __u64 flags) = (void *) 23; + +/* + * bpf_get_route_realm + * + * Retrieve the realm or the route, that is to say the + * **tclassid** field of the destination for the *skb*. The + * identifier retrieved is a user-provided tag, similar to the + * one used with the net_cls cgroup (see description for + * **bpf_get_cgroup_classid**\ () helper), but here this tag is + * held by a route (a destination entry), not by a task. + * + * Retrieving this identifier works with the clsact TC egress hook + * (see also **tc-bpf(8)**), or alternatively on conventional + * classful egress qdiscs, but not on TC ingress path. In case of + * clsact TC egress hook, this has the advantage that, internally, + * the destination entry has not been dropped yet in the transmit + * path. Therefore, the destination entry does not need to be + * artificially held via **netif_keep_dst**\ () for a classful + * qdisc until the *skb* is freed. + * + * This helper is available only if the kernel was compiled with + * **CONFIG_IP_ROUTE_CLASSID** configuration option. + * + * Returns + * The realm of the route for the packet associated to *skb*, or 0 + * if none was found. + */ +static __u32 (*bpf_get_route_realm)(struct __sk_buff *skb) = (void *) 24; + +/* + * bpf_perf_event_output + * + * Write raw *data* blob into a special BPF perf event held by + * *map* of type **BPF_MAP_TYPE_PERF_EVENT_ARRAY**. This perf + * event must have the following attributes: **PERF_SAMPLE_RAW** + * as **sample_type**, **PERF_TYPE_SOFTWARE** as **type**, and + * **PERF_COUNT_SW_BPF_OUTPUT** as **config**. + * + * The *flags* are used to indicate the index in *map* for which + * the value must be put, masked with **BPF_F_INDEX_MASK**. + * Alternatively, *flags* can be set to **BPF_F_CURRENT_CPU** + * to indicate that the index of the current CPU core should be + * used. + * + * The value to write, of *size*, is passed through eBPF stack and + * pointed by *data*. + * + * The context of the program *ctx* needs also be passed to the + * helper. + * + * On user space, a program willing to read the values needs to + * call **perf_event_open**\ () on the perf event (either for + * one or for all CPUs) and to store the file descriptor into the + * *map*. This must be done before the eBPF program can send data + * into it. An example is available in file + * *samples/bpf/trace_output_user.c* in the Linux kernel source + * tree (the eBPF program counterpart is in + * *samples/bpf/trace_output_kern.c*). + * + * **bpf_perf_event_output**\ () achieves better performance + * than **bpf_trace_printk**\ () for sharing data with user + * space, and is much better suitable for streaming data from eBPF + * programs. + * + * Note that this helper is not restricted to tracing use cases + * and can be used with programs attached to TC or XDP as well, + * where it allows for passing data to user space listeners. Data + * can be: + * + * * Only custom structs, + * * Only the packet payload, or + * * A combination of both. + * + * Returns + * 0 on success, or a negative error in case of failure. + */ +static long (*bpf_perf_event_output)(void *ctx, void *map, __u64 flags, void *data, __u64 size) = (void *) 25; + +/* + * bpf_skb_load_bytes + * + * This helper was provided as an easy way to load data from a + * packet. It can be used to load *len* bytes from *offset* from + * the packet associated to *skb*, into the buffer pointed by + * *to*. + * + * Since Linux 4.7, usage of this helper has mostly been replaced + * by "direct packet access", enabling packet data to be + * manipulated with *skb*\ **->data** and *skb*\ **->data_end** + * pointing respectively to the first byte of packet data and to + * the byte after the last byte of packet data. However, it + * remains useful if one wishes to read large quantities of data + * at once from a packet into the eBPF stack. + * + * Returns + * 0 on success, or a negative error in case of failure. + */ +static long (*bpf_skb_load_bytes)(const void *skb, __u32 offset, void *to, __u32 len) = (void *) 26; + +/* + * bpf_get_stackid + * + * Walk a user or a kernel stack and return its id. To achieve + * this, the helper needs *ctx*, which is a pointer to the context + * on which the tracing program is executed, and a pointer to a + * *map* of type **BPF_MAP_TYPE_STACK_TRACE**. + * + * The last argument, *flags*, holds the number of stack frames to + * skip (from 0 to 255), masked with + * **BPF_F_SKIP_FIELD_MASK**. The next bits can be used to set + * a combination of the following flags: + * + * **BPF_F_USER_STACK** + * Collect a user space stack instead of a kernel stack. + * **BPF_F_FAST_STACK_CMP** + * Compare stacks by hash only. + * **BPF_F_REUSE_STACKID** + * If two different stacks hash into the same *stackid*, + * discard the old one. + * + * The stack id retrieved is a 32 bit long integer handle which + * can be further combined with other data (including other stack + * ids) and used as a key into maps. This can be useful for + * generating a variety of graphs (such as flame graphs or off-cpu + * graphs). + * + * For walking a stack, this helper is an improvement over + * **bpf_probe_read**\ (), which can be used with unrolled loops + * but is not efficient and consumes a lot of eBPF instructions. + * Instead, **bpf_get_stackid**\ () can collect up to + * **PERF_MAX_STACK_DEPTH** both kernel and user frames. Note that + * this limit can be controlled with the **sysctl** program, and + * that it should be manually increased in order to profile long + * user stacks (such as stacks for Java programs). To do so, use: + * + * :: + * + * # sysctl kernel.perf_event_max_stack= + * + * Returns + * The positive or null stack id on success, or a negative error + * in case of failure. + */ +static long (*bpf_get_stackid)(void *ctx, void *map, __u64 flags) = (void *) 27; + +/* + * bpf_csum_diff + * + * Compute a checksum difference, from the raw buffer pointed by + * *from*, of length *from_size* (that must be a multiple of 4), + * towards the raw buffer pointed by *to*, of size *to_size* + * (same remark). An optional *seed* can be added to the value + * (this can be cascaded, the seed may come from a previous call + * to the helper). + * + * This is flexible enough to be used in several ways: + * + * * With *from_size* == 0, *to_size* > 0 and *seed* set to + * checksum, it can be used when pushing new data. + * * With *from_size* > 0, *to_size* == 0 and *seed* set to + * checksum, it can be used when removing data from a packet. + * * With *from_size* > 0, *to_size* > 0 and *seed* set to 0, it + * can be used to compute a diff. Note that *from_size* and + * *to_size* do not need to be equal. + * + * This helper can be used in combination with + * **bpf_l3_csum_replace**\ () and **bpf_l4_csum_replace**\ (), to + * which one can feed in the difference computed with + * **bpf_csum_diff**\ (). + * + * Returns + * The checksum result, or a negative error code in case of + * failure. + */ +static __s64 (*bpf_csum_diff)(__be32 *from, __u32 from_size, __be32 *to, __u32 to_size, __wsum seed) = (void *) 28; + +/* + * bpf_skb_get_tunnel_opt + * + * Retrieve tunnel options metadata for the packet associated to + * *skb*, and store the raw tunnel option data to the buffer *opt* + * of *size*. + * + * This helper can be used with encapsulation devices that can + * operate in "collect metadata" mode (please refer to the related + * note in the description of **bpf_skb_get_tunnel_key**\ () for + * more details). A particular example where this can be used is + * in combination with the Geneve encapsulation protocol, where it + * allows for pushing (with **bpf_skb_get_tunnel_opt**\ () helper) + * and retrieving arbitrary TLVs (Type-Length-Value headers) from + * the eBPF program. This allows for full customization of these + * headers. + * + * Returns + * The size of the option data retrieved. + */ +static long (*bpf_skb_get_tunnel_opt)(struct __sk_buff *skb, void *opt, __u32 size) = (void *) 29; + +/* + * bpf_skb_set_tunnel_opt + * + * Set tunnel options metadata for the packet associated to *skb* + * to the option data contained in the raw buffer *opt* of *size*. + * + * See also the description of the **bpf_skb_get_tunnel_opt**\ () + * helper for additional information. + * + * Returns + * 0 on success, or a negative error in case of failure. + */ +static long (*bpf_skb_set_tunnel_opt)(struct __sk_buff *skb, void *opt, __u32 size) = (void *) 30; + +/* + * bpf_skb_change_proto + * + * Change the protocol of the *skb* to *proto*. Currently + * supported are transition from IPv4 to IPv6, and from IPv6 to + * IPv4. The helper takes care of the groundwork for the + * transition, including resizing the socket buffer. The eBPF + * program is expected to fill the new headers, if any, via + * **skb_store_bytes**\ () and to recompute the checksums with + * **bpf_l3_csum_replace**\ () and **bpf_l4_csum_replace**\ + * (). The main case for this helper is to perform NAT64 + * operations out of an eBPF program. + * + * Internally, the GSO type is marked as dodgy so that headers are + * checked and segments are recalculated by the GSO/GRO engine. + * The size for GSO target is adapted as well. + * + * All values for *flags* are reserved for future usage, and must + * be left at zero. + * + * A call to this helper is susceptible to change the underlying + * packet buffer. Therefore, at load time, all checks on pointers + * previously done by the verifier are invalidated and must be + * performed again, if the helper is used in combination with + * direct packet access. + * + * Returns + * 0 on success, or a negative error in case of failure. + */ +static long (*bpf_skb_change_proto)(struct __sk_buff *skb, __be16 proto, __u64 flags) = (void *) 31; + +/* + * bpf_skb_change_type + * + * Change the packet type for the packet associated to *skb*. This + * comes down to setting *skb*\ **->pkt_type** to *type*, except + * the eBPF program does not have a write access to *skb*\ + * **->pkt_type** beside this helper. Using a helper here allows + * for graceful handling of errors. + * + * The major use case is to change incoming *skb*s to + * **PACKET_HOST** in a programmatic way instead of having to + * recirculate via **redirect**\ (..., **BPF_F_INGRESS**), for + * example. + * + * Note that *type* only allows certain values. At this time, they + * are: + * + * **PACKET_HOST** + * Packet is for us. + * **PACKET_BROADCAST** + * Send packet to all. + * **PACKET_MULTICAST** + * Send packet to group. + * **PACKET_OTHERHOST** + * Send packet to someone else. + * + * Returns + * 0 on success, or a negative error in case of failure. + */ +static long (*bpf_skb_change_type)(struct __sk_buff *skb, __u32 type) = (void *) 32; + +/* + * bpf_skb_under_cgroup + * + * Check whether *skb* is a descendant of the cgroup2 held by + * *map* of type **BPF_MAP_TYPE_CGROUP_ARRAY**, at *index*. + * + * Returns + * The return value depends on the result of the test, and can be: + * + * * 0, if the *skb* failed the cgroup2 descendant test. + * * 1, if the *skb* succeeded the cgroup2 descendant test. + * * A negative error code, if an error occurred. + */ +static long (*bpf_skb_under_cgroup)(struct __sk_buff *skb, void *map, __u32 index) = (void *) 33; + +/* + * bpf_get_hash_recalc + * + * Retrieve the hash of the packet, *skb*\ **->hash**. If it is + * not set, in particular if the hash was cleared due to mangling, + * recompute this hash. Later accesses to the hash can be done + * directly with *skb*\ **->hash**. + * + * Calling **bpf_set_hash_invalid**\ (), changing a packet + * prototype with **bpf_skb_change_proto**\ (), or calling + * **bpf_skb_store_bytes**\ () with the + * **BPF_F_INVALIDATE_HASH** are actions susceptible to clear + * the hash and to trigger a new computation for the next call to + * **bpf_get_hash_recalc**\ (). + * + * Returns + * The 32-bit hash. + */ +static __u32 (*bpf_get_hash_recalc)(struct __sk_buff *skb) = (void *) 34; + +/* + * bpf_get_current_task + * + * + * Returns + * A pointer to the current task struct. + */ +static __u64 (*bpf_get_current_task)(void) = (void *) 35; + +/* + * bpf_probe_write_user + * + * Attempt in a safe way to write *len* bytes from the buffer + * *src* to *dst* in memory. It only works for threads that are in + * user context, and *dst* must be a valid user space address. + * + * This helper should not be used to implement any kind of + * security mechanism because of TOC-TOU attacks, but rather to + * debug, divert, and manipulate execution of semi-cooperative + * processes. + * + * Keep in mind that this feature is meant for experiments, and it + * has a risk of crashing the system and running programs. + * Therefore, when an eBPF program using this helper is attached, + * a warning including PID and process name is printed to kernel + * logs. + * + * Returns + * 0 on success, or a negative error in case of failure. + */ +static long (*bpf_probe_write_user)(void *dst, const void *src, __u32 len) = (void *) 36; + +/* + * bpf_current_task_under_cgroup + * + * Check whether the probe is being run is the context of a given + * subset of the cgroup2 hierarchy. The cgroup2 to test is held by + * *map* of type **BPF_MAP_TYPE_CGROUP_ARRAY**, at *index*. + * + * Returns + * The return value depends on the result of the test, and can be: + * + * * 0, if current task belongs to the cgroup2. + * * 1, if current task does not belong to the cgroup2. + * * A negative error code, if an error occurred. + */ +static long (*bpf_current_task_under_cgroup)(void *map, __u32 index) = (void *) 37; + +/* + * bpf_skb_change_tail + * + * Resize (trim or grow) the packet associated to *skb* to the + * new *len*. The *flags* are reserved for future usage, and must + * be left at zero. + * + * The basic idea is that the helper performs the needed work to + * change the size of the packet, then the eBPF program rewrites + * the rest via helpers like **bpf_skb_store_bytes**\ (), + * **bpf_l3_csum_replace**\ (), **bpf_l3_csum_replace**\ () + * and others. This helper is a slow path utility intended for + * replies with control messages. And because it is targeted for + * slow path, the helper itself can afford to be slow: it + * implicitly linearizes, unclones and drops offloads from the + * *skb*. + * + * A call to this helper is susceptible to change the underlying + * packet buffer. Therefore, at load time, all checks on pointers + * previously done by the verifier are invalidated and must be + * performed again, if the helper is used in combination with + * direct packet access. + * + * Returns + * 0 on success, or a negative error in case of failure. + */ +static long (*bpf_skb_change_tail)(struct __sk_buff *skb, __u32 len, __u64 flags) = (void *) 38; + +/* + * bpf_skb_pull_data + * + * Pull in non-linear data in case the *skb* is non-linear and not + * all of *len* are part of the linear section. Make *len* bytes + * from *skb* readable and writable. If a zero value is passed for + * *len*, then the whole length of the *skb* is pulled. + * + * This helper is only needed for reading and writing with direct + * packet access. + * + * For direct packet access, testing that offsets to access + * are within packet boundaries (test on *skb*\ **->data_end**) is + * susceptible to fail if offsets are invalid, or if the requested + * data is in non-linear parts of the *skb*. On failure the + * program can just bail out, or in the case of a non-linear + * buffer, use a helper to make the data available. The + * **bpf_skb_load_bytes**\ () helper is a first solution to access + * the data. Another one consists in using **bpf_skb_pull_data** + * to pull in once the non-linear parts, then retesting and + * eventually access the data. + * + * At the same time, this also makes sure the *skb* is uncloned, + * which is a necessary condition for direct write. As this needs + * to be an invariant for the write part only, the verifier + * detects writes and adds a prologue that is calling + * **bpf_skb_pull_data()** to effectively unclone the *skb* from + * the very beginning in case it is indeed cloned. + * + * A call to this helper is susceptible to change the underlying + * packet buffer. Therefore, at load time, all checks on pointers + * previously done by the verifier are invalidated and must be + * performed again, if the helper is used in combination with + * direct packet access. + * + * Returns + * 0 on success, or a negative error in case of failure. + */ +static long (*bpf_skb_pull_data)(struct __sk_buff *skb, __u32 len) = (void *) 39; + +/* + * bpf_csum_update + * + * Add the checksum *csum* into *skb*\ **->csum** in case the + * driver has supplied a checksum for the entire packet into that + * field. Return an error otherwise. This helper is intended to be + * used in combination with **bpf_csum_diff**\ (), in particular + * when the checksum needs to be updated after data has been + * written into the packet through direct packet access. + * + * Returns + * The checksum on success, or a negative error code in case of + * failure. + */ +static __s64 (*bpf_csum_update)(struct __sk_buff *skb, __wsum csum) = (void *) 40; + +/* + * bpf_set_hash_invalid + * + * Invalidate the current *skb*\ **->hash**. It can be used after + * mangling on headers through direct packet access, in order to + * indicate that the hash is outdated and to trigger a + * recalculation the next time the kernel tries to access this + * hash or when the **bpf_get_hash_recalc**\ () helper is called. + * + */ +static void (*bpf_set_hash_invalid)(struct __sk_buff *skb) = (void *) 41; + +/* + * bpf_get_numa_node_id + * + * Return the id of the current NUMA node. The primary use case + * for this helper is the selection of sockets for the local NUMA + * node, when the program is attached to sockets using the + * **SO_ATTACH_REUSEPORT_EBPF** option (see also **socket(7)**), + * but the helper is also available to other eBPF program types, + * similarly to **bpf_get_smp_processor_id**\ (). + * + * Returns + * The id of current NUMA node. + */ +static long (*bpf_get_numa_node_id)(void) = (void *) 42; + +/* + * bpf_skb_change_head + * + * Grows headroom of packet associated to *skb* and adjusts the + * offset of the MAC header accordingly, adding *len* bytes of + * space. It automatically extends and reallocates memory as + * required. + * + * This helper can be used on a layer 3 *skb* to push a MAC header + * for redirection into a layer 2 device. + * + * All values for *flags* are reserved for future usage, and must + * be left at zero. + * + * A call to this helper is susceptible to change the underlying + * packet buffer. Therefore, at load time, all checks on pointers + * previously done by the verifier are invalidated and must be + * performed again, if the helper is used in combination with + * direct packet access. + * + * Returns + * 0 on success, or a negative error in case of failure. + */ +static long (*bpf_skb_change_head)(struct __sk_buff *skb, __u32 len, __u64 flags) = (void *) 43; + +/* + * bpf_xdp_adjust_head + * + * Adjust (move) *xdp_md*\ **->data** by *delta* bytes. Note that + * it is possible to use a negative value for *delta*. This helper + * can be used to prepare the packet for pushing or popping + * headers. + * + * A call to this helper is susceptible to change the underlying + * packet buffer. Therefore, at load time, all checks on pointers + * previously done by the verifier are invalidated and must be + * performed again, if the helper is used in combination with + * direct packet access. + * + * Returns + * 0 on success, or a negative error in case of failure. + */ +static long (*bpf_xdp_adjust_head)(struct xdp_md *xdp_md, int delta) = (void *) 44; + +/* + * bpf_probe_read_str + * + * Copy a NUL terminated string from an unsafe kernel address + * *unsafe_ptr* to *dst*. See **bpf_probe_read_kernel_str**\ () for + * more details. + * + * Generally, use **bpf_probe_read_user_str**\ () or + * **bpf_probe_read_kernel_str**\ () instead. + * + * Returns + * On success, the strictly positive length of the string, + * including the trailing NUL character. On error, a negative + * value. + */ +static long (*bpf_probe_read_str)(void *dst, __u32 size, const void *unsafe_ptr) = (void *) 45; + +/* + * bpf_get_socket_cookie + * + * If the **struct sk_buff** pointed by *skb* has a known socket, + * retrieve the cookie (generated by the kernel) of this socket. + * If no cookie has been set yet, generate a new cookie. Once + * generated, the socket cookie remains stable for the life of the + * socket. This helper can be useful for monitoring per socket + * networking traffic statistics as it provides a global socket + * identifier that can be assumed unique. + * + * Returns + * A 8-byte long unique number on success, or 0 if the socket + * field is missing inside *skb*. + */ +static __u64 (*bpf_get_socket_cookie)(void *ctx) = (void *) 46; + +/* + * bpf_get_socket_uid + * + * + * Returns + * The owner UID of the socket associated to *skb*. If the socket + * is **NULL**, or if it is not a full socket (i.e. if it is a + * time-wait or a request socket instead), **overflowuid** value + * is returned (note that **overflowuid** might also be the actual + * UID value for the socket). + */ +static __u32 (*bpf_get_socket_uid)(struct __sk_buff *skb) = (void *) 47; + +/* + * bpf_set_hash + * + * Set the full hash for *skb* (set the field *skb*\ **->hash**) + * to value *hash*. + * + * Returns + * 0 + */ +static long (*bpf_set_hash)(struct __sk_buff *skb, __u32 hash) = (void *) 48; + +/* + * bpf_setsockopt + * + * Emulate a call to **setsockopt()** on the socket associated to + * *bpf_socket*, which must be a full socket. The *level* at + * which the option resides and the name *optname* of the option + * must be specified, see **setsockopt(2)** for more information. + * The option value of length *optlen* is pointed by *optval*. + * + * *bpf_socket* should be one of the following: + * + * * **struct bpf_sock_ops** for **BPF_PROG_TYPE_SOCK_OPS**. + * * **struct bpf_sock_addr** for **BPF_CGROUP_INET4_CONNECT** + * and **BPF_CGROUP_INET6_CONNECT**. + * + * This helper actually implements a subset of **setsockopt()**. + * It supports the following *level*\ s: + * + * * **SOL_SOCKET**, which supports the following *optname*\ s: + * **SO_RCVBUF**, **SO_SNDBUF**, **SO_MAX_PACING_RATE**, + * **SO_PRIORITY**, **SO_RCVLOWAT**, **SO_MARK**, + * **SO_BINDTODEVICE**, **SO_KEEPALIVE**. + * * **IPPROTO_TCP**, which supports the following *optname*\ s: + * **TCP_CONGESTION**, **TCP_BPF_IW**, + * **TCP_BPF_SNDCWND_CLAMP**, **TCP_SAVE_SYN**, + * **TCP_KEEPIDLE**, **TCP_KEEPINTVL**, **TCP_KEEPCNT**, + * **TCP_SYNCNT**, **TCP_USER_TIMEOUT**, **TCP_NOTSENT_LOWAT**. + * * **IPPROTO_IP**, which supports *optname* **IP_TOS**. + * * **IPPROTO_IPV6**, which supports *optname* **IPV6_TCLASS**. + * + * Returns + * 0 on success, or a negative error in case of failure. + */ +static long (*bpf_setsockopt)(void *bpf_socket, int level, int optname, void *optval, int optlen) = (void *) 49; + +/* + * bpf_skb_adjust_room + * + * Grow or shrink the room for data in the packet associated to + * *skb* by *len_diff*, and according to the selected *mode*. + * + * By default, the helper will reset any offloaded checksum + * indicator of the skb to CHECKSUM_NONE. This can be avoided + * by the following flag: + * + * * **BPF_F_ADJ_ROOM_NO_CSUM_RESET**: Do not reset offloaded + * checksum data of the skb to CHECKSUM_NONE. + * + * There are two supported modes at this time: + * + * * **BPF_ADJ_ROOM_MAC**: Adjust room at the mac layer + * (room space is added or removed below the layer 2 header). + * + * * **BPF_ADJ_ROOM_NET**: Adjust room at the network layer + * (room space is added or removed below the layer 3 header). + * + * The following flags are supported at this time: + * + * * **BPF_F_ADJ_ROOM_FIXED_GSO**: Do not adjust gso_size. + * Adjusting mss in this way is not allowed for datagrams. + * + * * **BPF_F_ADJ_ROOM_ENCAP_L3_IPV4**, + * **BPF_F_ADJ_ROOM_ENCAP_L3_IPV6**: + * Any new space is reserved to hold a tunnel header. + * Configure skb offsets and other fields accordingly. + * + * * **BPF_F_ADJ_ROOM_ENCAP_L4_GRE**, + * **BPF_F_ADJ_ROOM_ENCAP_L4_UDP**: + * Use with ENCAP_L3 flags to further specify the tunnel type. + * + * * **BPF_F_ADJ_ROOM_ENCAP_L2**\ (*len*): + * Use with ENCAP_L3/L4 flags to further specify the tunnel + * type; *len* is the length of the inner MAC header. + * + * * **BPF_F_ADJ_ROOM_ENCAP_L2_ETH**: + * Use with BPF_F_ADJ_ROOM_ENCAP_L2 flag to further specify the + * L2 type as Ethernet. + * + * A call to this helper is susceptible to change the underlying + * packet buffer. Therefore, at load time, all checks on pointers + * previously done by the verifier are invalidated and must be + * performed again, if the helper is used in combination with + * direct packet access. + * + * Returns + * 0 on success, or a negative error in case of failure. + */ +static long (*bpf_skb_adjust_room)(struct __sk_buff *skb, __s32 len_diff, __u32 mode, __u64 flags) = (void *) 50; + +/* + * bpf_redirect_map + * + * Redirect the packet to the endpoint referenced by *map* at + * index *key*. Depending on its type, this *map* can contain + * references to net devices (for forwarding packets through other + * ports), or to CPUs (for redirecting XDP frames to another CPU; + * but this is only implemented for native XDP (with driver + * support) as of this writing). + * + * The lower two bits of *flags* are used as the return code if + * the map lookup fails. This is so that the return value can be + * one of the XDP program return codes up to **XDP_TX**, as chosen + * by the caller. The higher bits of *flags* can be set to + * BPF_F_BROADCAST or BPF_F_EXCLUDE_INGRESS as defined below. + * + * With BPF_F_BROADCAST the packet will be broadcasted to all the + * interfaces in the map, with BPF_F_EXCLUDE_INGRESS the ingress + * interface will be excluded when do broadcasting. + * + * See also **bpf_redirect**\ (), which only supports redirecting + * to an ifindex, but doesn't require a map to do so. + * + * Returns + * **XDP_REDIRECT** on success, or the value of the two lower bits + * of the *flags* argument on error. + */ +static long (*bpf_redirect_map)(void *map, __u32 key, __u64 flags) = (void *) 51; + +/* + * bpf_sk_redirect_map + * + * Redirect the packet to the socket referenced by *map* (of type + * **BPF_MAP_TYPE_SOCKMAP**) at index *key*. Both ingress and + * egress interfaces can be used for redirection. The + * **BPF_F_INGRESS** value in *flags* is used to make the + * distinction (ingress path is selected if the flag is present, + * egress path otherwise). This is the only flag supported for now. + * + * Returns + * **SK_PASS** on success, or **SK_DROP** on error. + */ +static long (*bpf_sk_redirect_map)(struct __sk_buff *skb, void *map, __u32 key, __u64 flags) = (void *) 52; + +/* + * bpf_sock_map_update + * + * Add an entry to, or update a *map* referencing sockets. The + * *skops* is used as a new value for the entry associated to + * *key*. *flags* is one of: + * + * **BPF_NOEXIST** + * The entry for *key* must not exist in the map. + * **BPF_EXIST** + * The entry for *key* must already exist in the map. + * **BPF_ANY** + * No condition on the existence of the entry for *key*. + * + * If the *map* has eBPF programs (parser and verdict), those will + * be inherited by the socket being added. If the socket is + * already attached to eBPF programs, this results in an error. + * + * Returns + * 0 on success, or a negative error in case of failure. + */ +static long (*bpf_sock_map_update)(struct bpf_sock_ops *skops, void *map, void *key, __u64 flags) = (void *) 53; + +/* + * bpf_xdp_adjust_meta + * + * Adjust the address pointed by *xdp_md*\ **->data_meta** by + * *delta* (which can be positive or negative). Note that this + * operation modifies the address stored in *xdp_md*\ **->data**, + * so the latter must be loaded only after the helper has been + * called. + * + * The use of *xdp_md*\ **->data_meta** is optional and programs + * are not required to use it. The rationale is that when the + * packet is processed with XDP (e.g. as DoS filter), it is + * possible to push further meta data along with it before passing + * to the stack, and to give the guarantee that an ingress eBPF + * program attached as a TC classifier on the same device can pick + * this up for further post-processing. Since TC works with socket + * buffers, it remains possible to set from XDP the **mark** or + * **priority** pointers, or other pointers for the socket buffer. + * Having this scratch space generic and programmable allows for + * more flexibility as the user is free to store whatever meta + * data they need. + * + * A call to this helper is susceptible to change the underlying + * packet buffer. Therefore, at load time, all checks on pointers + * previously done by the verifier are invalidated and must be + * performed again, if the helper is used in combination with + * direct packet access. + * + * Returns + * 0 on success, or a negative error in case of failure. + */ +static long (*bpf_xdp_adjust_meta)(struct xdp_md *xdp_md, int delta) = (void *) 54; + +/* + * bpf_perf_event_read_value + * + * Read the value of a perf event counter, and store it into *buf* + * of size *buf_size*. This helper relies on a *map* of type + * **BPF_MAP_TYPE_PERF_EVENT_ARRAY**. The nature of the perf event + * counter is selected when *map* is updated with perf event file + * descriptors. The *map* is an array whose size is the number of + * available CPUs, and each cell contains a value relative to one + * CPU. The value to retrieve is indicated by *flags*, that + * contains the index of the CPU to look up, masked with + * **BPF_F_INDEX_MASK**. Alternatively, *flags* can be set to + * **BPF_F_CURRENT_CPU** to indicate that the value for the + * current CPU should be retrieved. + * + * This helper behaves in a way close to + * **bpf_perf_event_read**\ () helper, save that instead of + * just returning the value observed, it fills the *buf* + * structure. This allows for additional data to be retrieved: in + * particular, the enabled and running times (in *buf*\ + * **->enabled** and *buf*\ **->running**, respectively) are + * copied. In general, **bpf_perf_event_read_value**\ () is + * recommended over **bpf_perf_event_read**\ (), which has some + * ABI issues and provides fewer functionalities. + * + * These values are interesting, because hardware PMU (Performance + * Monitoring Unit) counters are limited resources. When there are + * more PMU based perf events opened than available counters, + * kernel will multiplex these events so each event gets certain + * percentage (but not all) of the PMU time. In case that + * multiplexing happens, the number of samples or counter value + * will not reflect the case compared to when no multiplexing + * occurs. This makes comparison between different runs difficult. + * Typically, the counter value should be normalized before + * comparing to other experiments. The usual normalization is done + * as follows. + * + * :: + * + * normalized_counter = counter * t_enabled / t_running + * + * Where t_enabled is the time enabled for event and t_running is + * the time running for event since last normalization. The + * enabled and running times are accumulated since the perf event + * open. To achieve scaling factor between two invocations of an + * eBPF program, users can use CPU id as the key (which is + * typical for perf array usage model) to remember the previous + * value and do the calculation inside the eBPF program. + * + * Returns + * 0 on success, or a negative error in case of failure. + */ +static long (*bpf_perf_event_read_value)(void *map, __u64 flags, struct bpf_perf_event_value *buf, __u32 buf_size) = (void *) 55; + +/* + * bpf_perf_prog_read_value + * + * For en eBPF program attached to a perf event, retrieve the + * value of the event counter associated to *ctx* and store it in + * the structure pointed by *buf* and of size *buf_size*. Enabled + * and running times are also stored in the structure (see + * description of helper **bpf_perf_event_read_value**\ () for + * more details). + * + * Returns + * 0 on success, or a negative error in case of failure. + */ +static long (*bpf_perf_prog_read_value)(struct bpf_perf_event_data *ctx, struct bpf_perf_event_value *buf, __u32 buf_size) = (void *) 56; + +/* + * bpf_getsockopt + * + * Emulate a call to **getsockopt()** on the socket associated to + * *bpf_socket*, which must be a full socket. The *level* at + * which the option resides and the name *optname* of the option + * must be specified, see **getsockopt(2)** for more information. + * The retrieved value is stored in the structure pointed by + * *opval* and of length *optlen*. + * + * *bpf_socket* should be one of the following: + * + * * **struct bpf_sock_ops** for **BPF_PROG_TYPE_SOCK_OPS**. + * * **struct bpf_sock_addr** for **BPF_CGROUP_INET4_CONNECT** + * and **BPF_CGROUP_INET6_CONNECT**. + * + * This helper actually implements a subset of **getsockopt()**. + * It supports the following *level*\ s: + * + * * **IPPROTO_TCP**, which supports *optname* + * **TCP_CONGESTION**. + * * **IPPROTO_IP**, which supports *optname* **IP_TOS**. + * * **IPPROTO_IPV6**, which supports *optname* **IPV6_TCLASS**. + * + * Returns + * 0 on success, or a negative error in case of failure. + */ +static long (*bpf_getsockopt)(void *bpf_socket, int level, int optname, void *optval, int optlen) = (void *) 57; + +/* + * bpf_override_return + * + * Used for error injection, this helper uses kprobes to override + * the return value of the probed function, and to set it to *rc*. + * The first argument is the context *regs* on which the kprobe + * works. + * + * This helper works by setting the PC (program counter) + * to an override function which is run in place of the original + * probed function. This means the probed function is not run at + * all. The replacement function just returns with the required + * value. + * + * This helper has security implications, and thus is subject to + * restrictions. It is only available if the kernel was compiled + * with the **CONFIG_BPF_KPROBE_OVERRIDE** configuration + * option, and in this case it only works on functions tagged with + * **ALLOW_ERROR_INJECTION** in the kernel code. + * + * Also, the helper is only available for the architectures having + * the CONFIG_FUNCTION_ERROR_INJECTION option. As of this writing, + * x86 architecture is the only one to support this feature. + * + * Returns + * 0 + */ +static long (*bpf_override_return)(struct pt_regs *regs, __u64 rc) = (void *) 58; + +/* + * bpf_sock_ops_cb_flags_set + * + * Attempt to set the value of the **bpf_sock_ops_cb_flags** field + * for the full TCP socket associated to *bpf_sock_ops* to + * *argval*. + * + * The primary use of this field is to determine if there should + * be calls to eBPF programs of type + * **BPF_PROG_TYPE_SOCK_OPS** at various points in the TCP + * code. A program of the same type can change its value, per + * connection and as necessary, when the connection is + * established. This field is directly accessible for reading, but + * this helper must be used for updates in order to return an + * error if an eBPF program tries to set a callback that is not + * supported in the current kernel. + * + * *argval* is a flag array which can combine these flags: + * + * * **BPF_SOCK_OPS_RTO_CB_FLAG** (retransmission time out) + * * **BPF_SOCK_OPS_RETRANS_CB_FLAG** (retransmission) + * * **BPF_SOCK_OPS_STATE_CB_FLAG** (TCP state change) + * * **BPF_SOCK_OPS_RTT_CB_FLAG** (every RTT) + * + * Therefore, this function can be used to clear a callback flag by + * setting the appropriate bit to zero. e.g. to disable the RTO + * callback: + * + * **bpf_sock_ops_cb_flags_set(bpf_sock,** + * **bpf_sock->bpf_sock_ops_cb_flags & ~BPF_SOCK_OPS_RTO_CB_FLAG)** + * + * Here are some examples of where one could call such eBPF + * program: + * + * * When RTO fires. + * * When a packet is retransmitted. + * * When the connection terminates. + * * When a packet is sent. + * * When a packet is received. + * + * Returns + * Code **-EINVAL** if the socket is not a full TCP socket; + * otherwise, a positive number containing the bits that could not + * be set is returned (which comes down to 0 if all bits were set + * as required). + */ +static long (*bpf_sock_ops_cb_flags_set)(struct bpf_sock_ops *bpf_sock, int argval) = (void *) 59; + +/* + * bpf_msg_redirect_map + * + * This helper is used in programs implementing policies at the + * socket level. If the message *msg* is allowed to pass (i.e. if + * the verdict eBPF program returns **SK_PASS**), redirect it to + * the socket referenced by *map* (of type + * **BPF_MAP_TYPE_SOCKMAP**) at index *key*. Both ingress and + * egress interfaces can be used for redirection. The + * **BPF_F_INGRESS** value in *flags* is used to make the + * distinction (ingress path is selected if the flag is present, + * egress path otherwise). This is the only flag supported for now. + * + * Returns + * **SK_PASS** on success, or **SK_DROP** on error. + */ +static long (*bpf_msg_redirect_map)(struct sk_msg_md *msg, void *map, __u32 key, __u64 flags) = (void *) 60; + +/* + * bpf_msg_apply_bytes + * + * For socket policies, apply the verdict of the eBPF program to + * the next *bytes* (number of bytes) of message *msg*. + * + * For example, this helper can be used in the following cases: + * + * * A single **sendmsg**\ () or **sendfile**\ () system call + * contains multiple logical messages that the eBPF program is + * supposed to read and for which it should apply a verdict. + * * An eBPF program only cares to read the first *bytes* of a + * *msg*. If the message has a large payload, then setting up + * and calling the eBPF program repeatedly for all bytes, even + * though the verdict is already known, would create unnecessary + * overhead. + * + * When called from within an eBPF program, the helper sets a + * counter internal to the BPF infrastructure, that is used to + * apply the last verdict to the next *bytes*. If *bytes* is + * smaller than the current data being processed from a + * **sendmsg**\ () or **sendfile**\ () system call, the first + * *bytes* will be sent and the eBPF program will be re-run with + * the pointer for start of data pointing to byte number *bytes* + * **+ 1**. If *bytes* is larger than the current data being + * processed, then the eBPF verdict will be applied to multiple + * **sendmsg**\ () or **sendfile**\ () calls until *bytes* are + * consumed. + * + * Note that if a socket closes with the internal counter holding + * a non-zero value, this is not a problem because data is not + * being buffered for *bytes* and is sent as it is received. + * + * Returns + * 0 + */ +static long (*bpf_msg_apply_bytes)(struct sk_msg_md *msg, __u32 bytes) = (void *) 61; + +/* + * bpf_msg_cork_bytes + * + * For socket policies, prevent the execution of the verdict eBPF + * program for message *msg* until *bytes* (byte number) have been + * accumulated. + * + * This can be used when one needs a specific number of bytes + * before a verdict can be assigned, even if the data spans + * multiple **sendmsg**\ () or **sendfile**\ () calls. The extreme + * case would be a user calling **sendmsg**\ () repeatedly with + * 1-byte long message segments. Obviously, this is bad for + * performance, but it is still valid. If the eBPF program needs + * *bytes* bytes to validate a header, this helper can be used to + * prevent the eBPF program to be called again until *bytes* have + * been accumulated. + * + * Returns + * 0 + */ +static long (*bpf_msg_cork_bytes)(struct sk_msg_md *msg, __u32 bytes) = (void *) 62; + +/* + * bpf_msg_pull_data + * + * For socket policies, pull in non-linear data from user space + * for *msg* and set pointers *msg*\ **->data** and *msg*\ + * **->data_end** to *start* and *end* bytes offsets into *msg*, + * respectively. + * + * If a program of type **BPF_PROG_TYPE_SK_MSG** is run on a + * *msg* it can only parse data that the (**data**, **data_end**) + * pointers have already consumed. For **sendmsg**\ () hooks this + * is likely the first scatterlist element. But for calls relying + * on the **sendpage** handler (e.g. **sendfile**\ ()) this will + * be the range (**0**, **0**) because the data is shared with + * user space and by default the objective is to avoid allowing + * user space to modify data while (or after) eBPF verdict is + * being decided. This helper can be used to pull in data and to + * set the start and end pointer to given values. Data will be + * copied if necessary (i.e. if data was not linear and if start + * and end pointers do not point to the same chunk). + * + * A call to this helper is susceptible to change the underlying + * packet buffer. Therefore, at load time, all checks on pointers + * previously done by the verifier are invalidated and must be + * performed again, if the helper is used in combination with + * direct packet access. + * + * All values for *flags* are reserved for future usage, and must + * be left at zero. + * + * Returns + * 0 on success, or a negative error in case of failure. + */ +static long (*bpf_msg_pull_data)(struct sk_msg_md *msg, __u32 start, __u32 end, __u64 flags) = (void *) 63; + +/* + * bpf_bind + * + * Bind the socket associated to *ctx* to the address pointed by + * *addr*, of length *addr_len*. This allows for making outgoing + * connection from the desired IP address, which can be useful for + * example when all processes inside a cgroup should use one + * single IP address on a host that has multiple IP configured. + * + * This helper works for IPv4 and IPv6, TCP and UDP sockets. The + * domain (*addr*\ **->sa_family**) must be **AF_INET** (or + * **AF_INET6**). It's advised to pass zero port (**sin_port** + * or **sin6_port**) which triggers IP_BIND_ADDRESS_NO_PORT-like + * behavior and lets the kernel efficiently pick up an unused + * port as long as 4-tuple is unique. Passing non-zero port might + * lead to degraded performance. + * + * Returns + * 0 on success, or a negative error in case of failure. + */ +static long (*bpf_bind)(struct bpf_sock_addr *ctx, struct sockaddr *addr, int addr_len) = (void *) 64; + +/* + * bpf_xdp_adjust_tail + * + * Adjust (move) *xdp_md*\ **->data_end** by *delta* bytes. It is + * possible to both shrink and grow the packet tail. + * Shrink done via *delta* being a negative integer. + * + * A call to this helper is susceptible to change the underlying + * packet buffer. Therefore, at load time, all checks on pointers + * previously done by the verifier are invalidated and must be + * performed again, if the helper is used in combination with + * direct packet access. + * + * Returns + * 0 on success, or a negative error in case of failure. + */ +static long (*bpf_xdp_adjust_tail)(struct xdp_md *xdp_md, int delta) = (void *) 65; + +/* + * bpf_skb_get_xfrm_state + * + * Retrieve the XFRM state (IP transform framework, see also + * **ip-xfrm(8)**) at *index* in XFRM "security path" for *skb*. + * + * The retrieved value is stored in the **struct bpf_xfrm_state** + * pointed by *xfrm_state* and of length *size*. + * + * All values for *flags* are reserved for future usage, and must + * be left at zero. + * + * This helper is available only if the kernel was compiled with + * **CONFIG_XFRM** configuration option. + * + * Returns + * 0 on success, or a negative error in case of failure. + */ +static long (*bpf_skb_get_xfrm_state)(struct __sk_buff *skb, __u32 index, struct bpf_xfrm_state *xfrm_state, __u32 size, __u64 flags) = (void *) 66; + +/* + * bpf_get_stack + * + * Return a user or a kernel stack in bpf program provided buffer. + * To achieve this, the helper needs *ctx*, which is a pointer + * to the context on which the tracing program is executed. + * To store the stacktrace, the bpf program provides *buf* with + * a nonnegative *size*. + * + * The last argument, *flags*, holds the number of stack frames to + * skip (from 0 to 255), masked with + * **BPF_F_SKIP_FIELD_MASK**. The next bits can be used to set + * the following flags: + * + * **BPF_F_USER_STACK** + * Collect a user space stack instead of a kernel stack. + * **BPF_F_USER_BUILD_ID** + * Collect buildid+offset instead of ips for user stack, + * only valid if **BPF_F_USER_STACK** is also specified. + * + * **bpf_get_stack**\ () can collect up to + * **PERF_MAX_STACK_DEPTH** both kernel and user frames, subject + * to sufficient large buffer size. Note that + * this limit can be controlled with the **sysctl** program, and + * that it should be manually increased in order to profile long + * user stacks (such as stacks for Java programs). To do so, use: + * + * :: + * + * # sysctl kernel.perf_event_max_stack= + * + * Returns + * A non-negative value equal to or less than *size* on success, + * or a negative error in case of failure. + */ +static long (*bpf_get_stack)(void *ctx, void *buf, __u32 size, __u64 flags) = (void *) 67; + +/* + * bpf_skb_load_bytes_relative + * + * This helper is similar to **bpf_skb_load_bytes**\ () in that + * it provides an easy way to load *len* bytes from *offset* + * from the packet associated to *skb*, into the buffer pointed + * by *to*. The difference to **bpf_skb_load_bytes**\ () is that + * a fifth argument *start_header* exists in order to select a + * base offset to start from. *start_header* can be one of: + * + * **BPF_HDR_START_MAC** + * Base offset to load data from is *skb*'s mac header. + * **BPF_HDR_START_NET** + * Base offset to load data from is *skb*'s network header. + * + * In general, "direct packet access" is the preferred method to + * access packet data, however, this helper is in particular useful + * in socket filters where *skb*\ **->data** does not always point + * to the start of the mac header and where "direct packet access" + * is not available. + * + * Returns + * 0 on success, or a negative error in case of failure. + */ +static long (*bpf_skb_load_bytes_relative)(const void *skb, __u32 offset, void *to, __u32 len, __u32 start_header) = (void *) 68; + +/* + * bpf_fib_lookup + * + * Do FIB lookup in kernel tables using parameters in *params*. + * If lookup is successful and result shows packet is to be + * forwarded, the neighbor tables are searched for the nexthop. + * If successful (ie., FIB lookup shows forwarding and nexthop + * is resolved), the nexthop address is returned in ipv4_dst + * or ipv6_dst based on family, smac is set to mac address of + * egress device, dmac is set to nexthop mac address, rt_metric + * is set to metric from route (IPv4/IPv6 only), and ifindex + * is set to the device index of the nexthop from the FIB lookup. + * + * *plen* argument is the size of the passed in struct. + * *flags* argument can be a combination of one or more of the + * following values: + * + * **BPF_FIB_LOOKUP_DIRECT** + * Do a direct table lookup vs full lookup using FIB + * rules. + * **BPF_FIB_LOOKUP_OUTPUT** + * Perform lookup from an egress perspective (default is + * ingress). + * + * *ctx* is either **struct xdp_md** for XDP programs or + * **struct sk_buff** tc cls_act programs. + * + * Returns + * * < 0 if any input argument is invalid + * * 0 on success (packet is forwarded, nexthop neighbor exists) + * * > 0 one of **BPF_FIB_LKUP_RET_** codes explaining why the + * packet is not forwarded or needs assist from full stack + * + * If lookup fails with BPF_FIB_LKUP_RET_FRAG_NEEDED, then the MTU + * was exceeded and output params->mtu_result contains the MTU. + */ +static long (*bpf_fib_lookup)(void *ctx, struct bpf_fib_lookup *params, int plen, __u32 flags) = (void *) 69; + +/* + * bpf_sock_hash_update + * + * Add an entry to, or update a sockhash *map* referencing sockets. + * The *skops* is used as a new value for the entry associated to + * *key*. *flags* is one of: + * + * **BPF_NOEXIST** + * The entry for *key* must not exist in the map. + * **BPF_EXIST** + * The entry for *key* must already exist in the map. + * **BPF_ANY** + * No condition on the existence of the entry for *key*. + * + * If the *map* has eBPF programs (parser and verdict), those will + * be inherited by the socket being added. If the socket is + * already attached to eBPF programs, this results in an error. + * + * Returns + * 0 on success, or a negative error in case of failure. + */ +static long (*bpf_sock_hash_update)(struct bpf_sock_ops *skops, void *map, void *key, __u64 flags) = (void *) 70; + +/* + * bpf_msg_redirect_hash + * + * This helper is used in programs implementing policies at the + * socket level. If the message *msg* is allowed to pass (i.e. if + * the verdict eBPF program returns **SK_PASS**), redirect it to + * the socket referenced by *map* (of type + * **BPF_MAP_TYPE_SOCKHASH**) using hash *key*. Both ingress and + * egress interfaces can be used for redirection. The + * **BPF_F_INGRESS** value in *flags* is used to make the + * distinction (ingress path is selected if the flag is present, + * egress path otherwise). This is the only flag supported for now. + * + * Returns + * **SK_PASS** on success, or **SK_DROP** on error. + */ +static long (*bpf_msg_redirect_hash)(struct sk_msg_md *msg, void *map, void *key, __u64 flags) = (void *) 71; + +/* + * bpf_sk_redirect_hash + * + * This helper is used in programs implementing policies at the + * skb socket level. If the sk_buff *skb* is allowed to pass (i.e. + * if the verdict eBPF program returns **SK_PASS**), redirect it + * to the socket referenced by *map* (of type + * **BPF_MAP_TYPE_SOCKHASH**) using hash *key*. Both ingress and + * egress interfaces can be used for redirection. The + * **BPF_F_INGRESS** value in *flags* is used to make the + * distinction (ingress path is selected if the flag is present, + * egress otherwise). This is the only flag supported for now. + * + * Returns + * **SK_PASS** on success, or **SK_DROP** on error. + */ +static long (*bpf_sk_redirect_hash)(struct __sk_buff *skb, void *map, void *key, __u64 flags) = (void *) 72; + +/* + * bpf_lwt_push_encap + * + * Encapsulate the packet associated to *skb* within a Layer 3 + * protocol header. This header is provided in the buffer at + * address *hdr*, with *len* its size in bytes. *type* indicates + * the protocol of the header and can be one of: + * + * **BPF_LWT_ENCAP_SEG6** + * IPv6 encapsulation with Segment Routing Header + * (**struct ipv6_sr_hdr**). *hdr* only contains the SRH, + * the IPv6 header is computed by the kernel. + * **BPF_LWT_ENCAP_SEG6_INLINE** + * Only works if *skb* contains an IPv6 packet. Insert a + * Segment Routing Header (**struct ipv6_sr_hdr**) inside + * the IPv6 header. + * **BPF_LWT_ENCAP_IP** + * IP encapsulation (GRE/GUE/IPIP/etc). The outer header + * must be IPv4 or IPv6, followed by zero or more + * additional headers, up to **LWT_BPF_MAX_HEADROOM** + * total bytes in all prepended headers. Please note that + * if **skb_is_gso**\ (*skb*) is true, no more than two + * headers can be prepended, and the inner header, if + * present, should be either GRE or UDP/GUE. + * + * **BPF_LWT_ENCAP_SEG6**\ \* types can be called by BPF programs + * of type **BPF_PROG_TYPE_LWT_IN**; **BPF_LWT_ENCAP_IP** type can + * be called by bpf programs of types **BPF_PROG_TYPE_LWT_IN** and + * **BPF_PROG_TYPE_LWT_XMIT**. + * + * A call to this helper is susceptible to change the underlying + * packet buffer. Therefore, at load time, all checks on pointers + * previously done by the verifier are invalidated and must be + * performed again, if the helper is used in combination with + * direct packet access. + * + * Returns + * 0 on success, or a negative error in case of failure. + */ +static long (*bpf_lwt_push_encap)(struct __sk_buff *skb, __u32 type, void *hdr, __u32 len) = (void *) 73; + +/* + * bpf_lwt_seg6_store_bytes + * + * Store *len* bytes from address *from* into the packet + * associated to *skb*, at *offset*. Only the flags, tag and TLVs + * inside the outermost IPv6 Segment Routing Header can be + * modified through this helper. + * + * A call to this helper is susceptible to change the underlying + * packet buffer. Therefore, at load time, all checks on pointers + * previously done by the verifier are invalidated and must be + * performed again, if the helper is used in combination with + * direct packet access. + * + * Returns + * 0 on success, or a negative error in case of failure. + */ +static long (*bpf_lwt_seg6_store_bytes)(struct __sk_buff *skb, __u32 offset, const void *from, __u32 len) = (void *) 74; + +/* + * bpf_lwt_seg6_adjust_srh + * + * Adjust the size allocated to TLVs in the outermost IPv6 + * Segment Routing Header contained in the packet associated to + * *skb*, at position *offset* by *delta* bytes. Only offsets + * after the segments are accepted. *delta* can be as well + * positive (growing) as negative (shrinking). + * + * A call to this helper is susceptible to change the underlying + * packet buffer. Therefore, at load time, all checks on pointers + * previously done by the verifier are invalidated and must be + * performed again, if the helper is used in combination with + * direct packet access. + * + * Returns + * 0 on success, or a negative error in case of failure. + */ +static long (*bpf_lwt_seg6_adjust_srh)(struct __sk_buff *skb, __u32 offset, __s32 delta) = (void *) 75; + +/* + * bpf_lwt_seg6_action + * + * Apply an IPv6 Segment Routing action of type *action* to the + * packet associated to *skb*. Each action takes a parameter + * contained at address *param*, and of length *param_len* bytes. + * *action* can be one of: + * + * **SEG6_LOCAL_ACTION_END_X** + * End.X action: Endpoint with Layer-3 cross-connect. + * Type of *param*: **struct in6_addr**. + * **SEG6_LOCAL_ACTION_END_T** + * End.T action: Endpoint with specific IPv6 table lookup. + * Type of *param*: **int**. + * **SEG6_LOCAL_ACTION_END_B6** + * End.B6 action: Endpoint bound to an SRv6 policy. + * Type of *param*: **struct ipv6_sr_hdr**. + * **SEG6_LOCAL_ACTION_END_B6_ENCAP** + * End.B6.Encap action: Endpoint bound to an SRv6 + * encapsulation policy. + * Type of *param*: **struct ipv6_sr_hdr**. + * + * A call to this helper is susceptible to change the underlying + * packet buffer. Therefore, at load time, all checks on pointers + * previously done by the verifier are invalidated and must be + * performed again, if the helper is used in combination with + * direct packet access. + * + * Returns + * 0 on success, or a negative error in case of failure. + */ +static long (*bpf_lwt_seg6_action)(struct __sk_buff *skb, __u32 action, void *param, __u32 param_len) = (void *) 76; + +/* + * bpf_rc_repeat + * + * This helper is used in programs implementing IR decoding, to + * report a successfully decoded repeat key message. This delays + * the generation of a key up event for previously generated + * key down event. + * + * Some IR protocols like NEC have a special IR message for + * repeating last button, for when a button is held down. + * + * The *ctx* should point to the lirc sample as passed into + * the program. + * + * This helper is only available is the kernel was compiled with + * the **CONFIG_BPF_LIRC_MODE2** configuration option set to + * "**y**". + * + * Returns + * 0 + */ +static long (*bpf_rc_repeat)(void *ctx) = (void *) 77; + +/* + * bpf_rc_keydown + * + * This helper is used in programs implementing IR decoding, to + * report a successfully decoded key press with *scancode*, + * *toggle* value in the given *protocol*. The scancode will be + * translated to a keycode using the rc keymap, and reported as + * an input key down event. After a period a key up event is + * generated. This period can be extended by calling either + * **bpf_rc_keydown**\ () again with the same values, or calling + * **bpf_rc_repeat**\ (). + * + * Some protocols include a toggle bit, in case the button was + * released and pressed again between consecutive scancodes. + * + * The *ctx* should point to the lirc sample as passed into + * the program. + * + * The *protocol* is the decoded protocol number (see + * **enum rc_proto** for some predefined values). + * + * This helper is only available is the kernel was compiled with + * the **CONFIG_BPF_LIRC_MODE2** configuration option set to + * "**y**". + * + * Returns + * 0 + */ +static long (*bpf_rc_keydown)(void *ctx, __u32 protocol, __u64 scancode, __u32 toggle) = (void *) 78; + +/* + * bpf_skb_cgroup_id + * + * Return the cgroup v2 id of the socket associated with the *skb*. + * This is roughly similar to the **bpf_get_cgroup_classid**\ () + * helper for cgroup v1 by providing a tag resp. identifier that + * can be matched on or used for map lookups e.g. to implement + * policy. The cgroup v2 id of a given path in the hierarchy is + * exposed in user space through the f_handle API in order to get + * to the same 64-bit id. + * + * This helper can be used on TC egress path, but not on ingress, + * and is available only if the kernel was compiled with the + * **CONFIG_SOCK_CGROUP_DATA** configuration option. + * + * Returns + * The id is returned or 0 in case the id could not be retrieved. + */ +static __u64 (*bpf_skb_cgroup_id)(struct __sk_buff *skb) = (void *) 79; + +/* + * bpf_get_current_cgroup_id + * + * + * Returns + * A 64-bit integer containing the current cgroup id based + * on the cgroup within which the current task is running. + */ +static __u64 (*bpf_get_current_cgroup_id)(void) = (void *) 80; + +/* + * bpf_get_local_storage + * + * Get the pointer to the local storage area. + * The type and the size of the local storage is defined + * by the *map* argument. + * The *flags* meaning is specific for each map type, + * and has to be 0 for cgroup local storage. + * + * Depending on the BPF program type, a local storage area + * can be shared between multiple instances of the BPF program, + * running simultaneously. + * + * A user should care about the synchronization by himself. + * For example, by using the **BPF_ATOMIC** instructions to alter + * the shared data. + * + * Returns + * A pointer to the local storage area. + */ +static void *(*bpf_get_local_storage)(void *map, __u64 flags) = (void *) 81; + +/* + * bpf_sk_select_reuseport + * + * Select a **SO_REUSEPORT** socket from a + * **BPF_MAP_TYPE_REUSEPORT_SOCKARRAY** *map*. + * It checks the selected socket is matching the incoming + * request in the socket buffer. + * + * Returns + * 0 on success, or a negative error in case of failure. + */ +static long (*bpf_sk_select_reuseport)(struct sk_reuseport_md *reuse, void *map, void *key, __u64 flags) = (void *) 82; + +/* + * bpf_skb_ancestor_cgroup_id + * + * Return id of cgroup v2 that is ancestor of cgroup associated + * with the *skb* at the *ancestor_level*. The root cgroup is at + * *ancestor_level* zero and each step down the hierarchy + * increments the level. If *ancestor_level* == level of cgroup + * associated with *skb*, then return value will be same as that + * of **bpf_skb_cgroup_id**\ (). + * + * The helper is useful to implement policies based on cgroups + * that are upper in hierarchy than immediate cgroup associated + * with *skb*. + * + * The format of returned id and helper limitations are same as in + * **bpf_skb_cgroup_id**\ (). + * + * Returns + * The id is returned or 0 in case the id could not be retrieved. + */ +static __u64 (*bpf_skb_ancestor_cgroup_id)(struct __sk_buff *skb, int ancestor_level) = (void *) 83; + +/* + * bpf_sk_lookup_tcp + * + * Look for TCP socket matching *tuple*, optionally in a child + * network namespace *netns*. The return value must be checked, + * and if non-**NULL**, released via **bpf_sk_release**\ (). + * + * The *ctx* should point to the context of the program, such as + * the skb or socket (depending on the hook in use). This is used + * to determine the base network namespace for the lookup. + * + * *tuple_size* must be one of: + * + * **sizeof**\ (*tuple*\ **->ipv4**) + * Look for an IPv4 socket. + * **sizeof**\ (*tuple*\ **->ipv6**) + * Look for an IPv6 socket. + * + * If the *netns* is a negative signed 32-bit integer, then the + * socket lookup table in the netns associated with the *ctx* + * will be used. For the TC hooks, this is the netns of the device + * in the skb. For socket hooks, this is the netns of the socket. + * If *netns* is any other signed 32-bit value greater than or + * equal to zero then it specifies the ID of the netns relative to + * the netns associated with the *ctx*. *netns* values beyond the + * range of 32-bit integers are reserved for future use. + * + * All values for *flags* are reserved for future usage, and must + * be left at zero. + * + * This helper is available only if the kernel was compiled with + * **CONFIG_NET** configuration option. + * + * Returns + * Pointer to **struct bpf_sock**, or **NULL** in case of failure. + * For sockets with reuseport option, the **struct bpf_sock** + * result is from *reuse*\ **->socks**\ [] using the hash of the + * tuple. + */ +static struct bpf_sock *(*bpf_sk_lookup_tcp)(void *ctx, struct bpf_sock_tuple *tuple, __u32 tuple_size, __u64 netns, __u64 flags) = (void *) 84; + +/* + * bpf_sk_lookup_udp + * + * Look for UDP socket matching *tuple*, optionally in a child + * network namespace *netns*. The return value must be checked, + * and if non-**NULL**, released via **bpf_sk_release**\ (). + * + * The *ctx* should point to the context of the program, such as + * the skb or socket (depending on the hook in use). This is used + * to determine the base network namespace for the lookup. + * + * *tuple_size* must be one of: + * + * **sizeof**\ (*tuple*\ **->ipv4**) + * Look for an IPv4 socket. + * **sizeof**\ (*tuple*\ **->ipv6**) + * Look for an IPv6 socket. + * + * If the *netns* is a negative signed 32-bit integer, then the + * socket lookup table in the netns associated with the *ctx* + * will be used. For the TC hooks, this is the netns of the device + * in the skb. For socket hooks, this is the netns of the socket. + * If *netns* is any other signed 32-bit value greater than or + * equal to zero then it specifies the ID of the netns relative to + * the netns associated with the *ctx*. *netns* values beyond the + * range of 32-bit integers are reserved for future use. + * + * All values for *flags* are reserved for future usage, and must + * be left at zero. + * + * This helper is available only if the kernel was compiled with + * **CONFIG_NET** configuration option. + * + * Returns + * Pointer to **struct bpf_sock**, or **NULL** in case of failure. + * For sockets with reuseport option, the **struct bpf_sock** + * result is from *reuse*\ **->socks**\ [] using the hash of the + * tuple. + */ +static struct bpf_sock *(*bpf_sk_lookup_udp)(void *ctx, struct bpf_sock_tuple *tuple, __u32 tuple_size, __u64 netns, __u64 flags) = (void *) 85; + +/* + * bpf_sk_release + * + * Release the reference held by *sock*. *sock* must be a + * non-**NULL** pointer that was returned from + * **bpf_sk_lookup_xxx**\ (). + * + * Returns + * 0 on success, or a negative error in case of failure. + */ +static long (*bpf_sk_release)(void *sock) = (void *) 86; + +/* + * bpf_map_push_elem + * + * Push an element *value* in *map*. *flags* is one of: + * + * **BPF_EXIST** + * If the queue/stack is full, the oldest element is + * removed to make room for this. + * + * Returns + * 0 on success, or a negative error in case of failure. + */ +static long (*bpf_map_push_elem)(void *map, const void *value, __u64 flags) = (void *) 87; + +/* + * bpf_map_pop_elem + * + * Pop an element from *map*. + * + * Returns + * 0 on success, or a negative error in case of failure. + */ +static long (*bpf_map_pop_elem)(void *map, void *value) = (void *) 88; + +/* + * bpf_map_peek_elem + * + * Get an element from *map* without removing it. + * + * Returns + * 0 on success, or a negative error in case of failure. + */ +static long (*bpf_map_peek_elem)(void *map, void *value) = (void *) 89; + +/* + * bpf_msg_push_data + * + * For socket policies, insert *len* bytes into *msg* at offset + * *start*. + * + * If a program of type **BPF_PROG_TYPE_SK_MSG** is run on a + * *msg* it may want to insert metadata or options into the *msg*. + * This can later be read and used by any of the lower layer BPF + * hooks. + * + * This helper may fail if under memory pressure (a malloc + * fails) in these cases BPF programs will get an appropriate + * error and BPF programs will need to handle them. + * + * Returns + * 0 on success, or a negative error in case of failure. + */ +static long (*bpf_msg_push_data)(struct sk_msg_md *msg, __u32 start, __u32 len, __u64 flags) = (void *) 90; + +/* + * bpf_msg_pop_data + * + * Will remove *len* bytes from a *msg* starting at byte *start*. + * This may result in **ENOMEM** errors under certain situations if + * an allocation and copy are required due to a full ring buffer. + * However, the helper will try to avoid doing the allocation + * if possible. Other errors can occur if input parameters are + * invalid either due to *start* byte not being valid part of *msg* + * payload and/or *pop* value being to large. + * + * Returns + * 0 on success, or a negative error in case of failure. + */ +static long (*bpf_msg_pop_data)(struct sk_msg_md *msg, __u32 start, __u32 len, __u64 flags) = (void *) 91; + +/* + * bpf_rc_pointer_rel + * + * This helper is used in programs implementing IR decoding, to + * report a successfully decoded pointer movement. + * + * The *ctx* should point to the lirc sample as passed into + * the program. + * + * This helper is only available is the kernel was compiled with + * the **CONFIG_BPF_LIRC_MODE2** configuration option set to + * "**y**". + * + * Returns + * 0 + */ +static long (*bpf_rc_pointer_rel)(void *ctx, __s32 rel_x, __s32 rel_y) = (void *) 92; + +/* + * bpf_spin_lock + * + * Acquire a spinlock represented by the pointer *lock*, which is + * stored as part of a value of a map. Taking the lock allows to + * safely update the rest of the fields in that value. The + * spinlock can (and must) later be released with a call to + * **bpf_spin_unlock**\ (\ *lock*\ ). + * + * Spinlocks in BPF programs come with a number of restrictions + * and constraints: + * + * * **bpf_spin_lock** objects are only allowed inside maps of + * types **BPF_MAP_TYPE_HASH** and **BPF_MAP_TYPE_ARRAY** (this + * list could be extended in the future). + * * BTF description of the map is mandatory. + * * The BPF program can take ONE lock at a time, since taking two + * or more could cause dead locks. + * * Only one **struct bpf_spin_lock** is allowed per map element. + * * When the lock is taken, calls (either BPF to BPF or helpers) + * are not allowed. + * * The **BPF_LD_ABS** and **BPF_LD_IND** instructions are not + * allowed inside a spinlock-ed region. + * * The BPF program MUST call **bpf_spin_unlock**\ () to release + * the lock, on all execution paths, before it returns. + * * The BPF program can access **struct bpf_spin_lock** only via + * the **bpf_spin_lock**\ () and **bpf_spin_unlock**\ () + * helpers. Loading or storing data into the **struct + * bpf_spin_lock** *lock*\ **;** field of a map is not allowed. + * * To use the **bpf_spin_lock**\ () helper, the BTF description + * of the map value must be a struct and have **struct + * bpf_spin_lock** *anyname*\ **;** field at the top level. + * Nested lock inside another struct is not allowed. + * * The **struct bpf_spin_lock** *lock* field in a map value must + * be aligned on a multiple of 4 bytes in that value. + * * Syscall with command **BPF_MAP_LOOKUP_ELEM** does not copy + * the **bpf_spin_lock** field to user space. + * * Syscall with command **BPF_MAP_UPDATE_ELEM**, or update from + * a BPF program, do not update the **bpf_spin_lock** field. + * * **bpf_spin_lock** cannot be on the stack or inside a + * networking packet (it can only be inside of a map values). + * * **bpf_spin_lock** is available to root only. + * * Tracing programs and socket filter programs cannot use + * **bpf_spin_lock**\ () due to insufficient preemption checks + * (but this may change in the future). + * * **bpf_spin_lock** is not allowed in inner maps of map-in-map. + * + * Returns + * 0 + */ +static long (*bpf_spin_lock)(struct bpf_spin_lock *lock) = (void *) 93; + +/* + * bpf_spin_unlock + * + * Release the *lock* previously locked by a call to + * **bpf_spin_lock**\ (\ *lock*\ ). + * + * Returns + * 0 + */ +static long (*bpf_spin_unlock)(struct bpf_spin_lock *lock) = (void *) 94; + +/* + * bpf_sk_fullsock + * + * This helper gets a **struct bpf_sock** pointer such + * that all the fields in this **bpf_sock** can be accessed. + * + * Returns + * A **struct bpf_sock** pointer on success, or **NULL** in + * case of failure. + */ +static struct bpf_sock *(*bpf_sk_fullsock)(struct bpf_sock *sk) = (void *) 95; + +/* + * bpf_tcp_sock + * + * This helper gets a **struct bpf_tcp_sock** pointer from a + * **struct bpf_sock** pointer. + * + * Returns + * A **struct bpf_tcp_sock** pointer on success, or **NULL** in + * case of failure. + */ +static struct bpf_tcp_sock *(*bpf_tcp_sock)(struct bpf_sock *sk) = (void *) 96; + +/* + * bpf_skb_ecn_set_ce + * + * Set ECN (Explicit Congestion Notification) field of IP header + * to **CE** (Congestion Encountered) if current value is **ECT** + * (ECN Capable Transport). Otherwise, do nothing. Works with IPv6 + * and IPv4. + * + * Returns + * 1 if the **CE** flag is set (either by the current helper call + * or because it was already present), 0 if it is not set. + */ +static long (*bpf_skb_ecn_set_ce)(struct __sk_buff *skb) = (void *) 97; + +/* + * bpf_get_listener_sock + * + * Return a **struct bpf_sock** pointer in **TCP_LISTEN** state. + * **bpf_sk_release**\ () is unnecessary and not allowed. + * + * Returns + * A **struct bpf_sock** pointer on success, or **NULL** in + * case of failure. + */ +static struct bpf_sock *(*bpf_get_listener_sock)(struct bpf_sock *sk) = (void *) 98; + +/* + * bpf_skc_lookup_tcp + * + * Look for TCP socket matching *tuple*, optionally in a child + * network namespace *netns*. The return value must be checked, + * and if non-**NULL**, released via **bpf_sk_release**\ (). + * + * This function is identical to **bpf_sk_lookup_tcp**\ (), except + * that it also returns timewait or request sockets. Use + * **bpf_sk_fullsock**\ () or **bpf_tcp_sock**\ () to access the + * full structure. + * + * This helper is available only if the kernel was compiled with + * **CONFIG_NET** configuration option. + * + * Returns + * Pointer to **struct bpf_sock**, or **NULL** in case of failure. + * For sockets with reuseport option, the **struct bpf_sock** + * result is from *reuse*\ **->socks**\ [] using the hash of the + * tuple. + */ +static struct bpf_sock *(*bpf_skc_lookup_tcp)(void *ctx, struct bpf_sock_tuple *tuple, __u32 tuple_size, __u64 netns, __u64 flags) = (void *) 99; + +/* + * bpf_tcp_check_syncookie + * + * Check whether *iph* and *th* contain a valid SYN cookie ACK for + * the listening socket in *sk*. + * + * *iph* points to the start of the IPv4 or IPv6 header, while + * *iph_len* contains **sizeof**\ (**struct iphdr**) or + * **sizeof**\ (**struct ip6hdr**). + * + * *th* points to the start of the TCP header, while *th_len* + * contains **sizeof**\ (**struct tcphdr**). + * + * Returns + * 0 if *iph* and *th* are a valid SYN cookie ACK, or a negative + * error otherwise. + */ +static long (*bpf_tcp_check_syncookie)(void *sk, void *iph, __u32 iph_len, struct tcphdr *th, __u32 th_len) = (void *) 100; + +/* + * bpf_sysctl_get_name + * + * Get name of sysctl in /proc/sys/ and copy it into provided by + * program buffer *buf* of size *buf_len*. + * + * The buffer is always NUL terminated, unless it's zero-sized. + * + * If *flags* is zero, full name (e.g. "net/ipv4/tcp_mem") is + * copied. Use **BPF_F_SYSCTL_BASE_NAME** flag to copy base name + * only (e.g. "tcp_mem"). + * + * Returns + * Number of character copied (not including the trailing NUL). + * + * **-E2BIG** if the buffer wasn't big enough (*buf* will contain + * truncated name in this case). + */ +static long (*bpf_sysctl_get_name)(struct bpf_sysctl *ctx, char *buf, unsigned long buf_len, __u64 flags) = (void *) 101; + +/* + * bpf_sysctl_get_current_value + * + * Get current value of sysctl as it is presented in /proc/sys + * (incl. newline, etc), and copy it as a string into provided + * by program buffer *buf* of size *buf_len*. + * + * The whole value is copied, no matter what file position user + * space issued e.g. sys_read at. + * + * The buffer is always NUL terminated, unless it's zero-sized. + * + * Returns + * Number of character copied (not including the trailing NUL). + * + * **-E2BIG** if the buffer wasn't big enough (*buf* will contain + * truncated name in this case). + * + * **-EINVAL** if current value was unavailable, e.g. because + * sysctl is uninitialized and read returns -EIO for it. + */ +static long (*bpf_sysctl_get_current_value)(struct bpf_sysctl *ctx, char *buf, unsigned long buf_len) = (void *) 102; + +/* + * bpf_sysctl_get_new_value + * + * Get new value being written by user space to sysctl (before + * the actual write happens) and copy it as a string into + * provided by program buffer *buf* of size *buf_len*. + * + * User space may write new value at file position > 0. + * + * The buffer is always NUL terminated, unless it's zero-sized. + * + * Returns + * Number of character copied (not including the trailing NUL). + * + * **-E2BIG** if the buffer wasn't big enough (*buf* will contain + * truncated name in this case). + * + * **-EINVAL** if sysctl is being read. + */ +static long (*bpf_sysctl_get_new_value)(struct bpf_sysctl *ctx, char *buf, unsigned long buf_len) = (void *) 103; + +/* + * bpf_sysctl_set_new_value + * + * Override new value being written by user space to sysctl with + * value provided by program in buffer *buf* of size *buf_len*. + * + * *buf* should contain a string in same form as provided by user + * space on sysctl write. + * + * User space may write new value at file position > 0. To override + * the whole sysctl value file position should be set to zero. + * + * Returns + * 0 on success. + * + * **-E2BIG** if the *buf_len* is too big. + * + * **-EINVAL** if sysctl is being read. + */ +static long (*bpf_sysctl_set_new_value)(struct bpf_sysctl *ctx, const char *buf, unsigned long buf_len) = (void *) 104; + +/* + * bpf_strtol + * + * Convert the initial part of the string from buffer *buf* of + * size *buf_len* to a long integer according to the given base + * and save the result in *res*. + * + * The string may begin with an arbitrary amount of white space + * (as determined by **isspace**\ (3)) followed by a single + * optional '**-**' sign. + * + * Five least significant bits of *flags* encode base, other bits + * are currently unused. + * + * Base must be either 8, 10, 16 or 0 to detect it automatically + * similar to user space **strtol**\ (3). + * + * Returns + * Number of characters consumed on success. Must be positive but + * no more than *buf_len*. + * + * **-EINVAL** if no valid digits were found or unsupported base + * was provided. + * + * **-ERANGE** if resulting value was out of range. + */ +static long (*bpf_strtol)(const char *buf, unsigned long buf_len, __u64 flags, long *res) = (void *) 105; + +/* + * bpf_strtoul + * + * Convert the initial part of the string from buffer *buf* of + * size *buf_len* to an unsigned long integer according to the + * given base and save the result in *res*. + * + * The string may begin with an arbitrary amount of white space + * (as determined by **isspace**\ (3)). + * + * Five least significant bits of *flags* encode base, other bits + * are currently unused. + * + * Base must be either 8, 10, 16 or 0 to detect it automatically + * similar to user space **strtoul**\ (3). + * + * Returns + * Number of characters consumed on success. Must be positive but + * no more than *buf_len*. + * + * **-EINVAL** if no valid digits were found or unsupported base + * was provided. + * + * **-ERANGE** if resulting value was out of range. + */ +static long (*bpf_strtoul)(const char *buf, unsigned long buf_len, __u64 flags, unsigned long *res) = (void *) 106; + +/* + * bpf_sk_storage_get + * + * Get a bpf-local-storage from a *sk*. + * + * Logically, it could be thought of getting the value from + * a *map* with *sk* as the **key**. From this + * perspective, the usage is not much different from + * **bpf_map_lookup_elem**\ (*map*, **&**\ *sk*) except this + * helper enforces the key must be a full socket and the map must + * be a **BPF_MAP_TYPE_SK_STORAGE** also. + * + * Underneath, the value is stored locally at *sk* instead of + * the *map*. The *map* is used as the bpf-local-storage + * "type". The bpf-local-storage "type" (i.e. the *map*) is + * searched against all bpf-local-storages residing at *sk*. + * + * *sk* is a kernel **struct sock** pointer for LSM program. + * *sk* is a **struct bpf_sock** pointer for other program types. + * + * An optional *flags* (**BPF_SK_STORAGE_GET_F_CREATE**) can be + * used such that a new bpf-local-storage will be + * created if one does not exist. *value* can be used + * together with **BPF_SK_STORAGE_GET_F_CREATE** to specify + * the initial value of a bpf-local-storage. If *value* is + * **NULL**, the new bpf-local-storage will be zero initialized. + * + * Returns + * A bpf-local-storage pointer is returned on success. + * + * **NULL** if not found or there was an error in adding + * a new bpf-local-storage. + */ +static void *(*bpf_sk_storage_get)(void *map, void *sk, void *value, __u64 flags) = (void *) 107; + +/* + * bpf_sk_storage_delete + * + * Delete a bpf-local-storage from a *sk*. + * + * Returns + * 0 on success. + * + * **-ENOENT** if the bpf-local-storage cannot be found. + * **-EINVAL** if sk is not a fullsock (e.g. a request_sock). + */ +static long (*bpf_sk_storage_delete)(void *map, void *sk) = (void *) 108; + +/* + * bpf_send_signal + * + * Send signal *sig* to the process of the current task. + * The signal may be delivered to any of this process's threads. + * + * Returns + * 0 on success or successfully queued. + * + * **-EBUSY** if work queue under nmi is full. + * + * **-EINVAL** if *sig* is invalid. + * + * **-EPERM** if no permission to send the *sig*. + * + * **-EAGAIN** if bpf program can try again. + */ +static long (*bpf_send_signal)(__u32 sig) = (void *) 109; + +/* + * bpf_tcp_gen_syncookie + * + * Try to issue a SYN cookie for the packet with corresponding + * IP/TCP headers, *iph* and *th*, on the listening socket in *sk*. + * + * *iph* points to the start of the IPv4 or IPv6 header, while + * *iph_len* contains **sizeof**\ (**struct iphdr**) or + * **sizeof**\ (**struct ip6hdr**). + * + * *th* points to the start of the TCP header, while *th_len* + * contains the length of the TCP header. + * + * Returns + * On success, lower 32 bits hold the generated SYN cookie in + * followed by 16 bits which hold the MSS value for that cookie, + * and the top 16 bits are unused. + * + * On failure, the returned value is one of the following: + * + * **-EINVAL** SYN cookie cannot be issued due to error + * + * **-ENOENT** SYN cookie should not be issued (no SYN flood) + * + * **-EOPNOTSUPP** kernel configuration does not enable SYN cookies + * + * **-EPROTONOSUPPORT** IP packet version is not 4 or 6 + */ +static __s64 (*bpf_tcp_gen_syncookie)(void *sk, void *iph, __u32 iph_len, struct tcphdr *th, __u32 th_len) = (void *) 110; + +/* + * bpf_skb_output + * + * Write raw *data* blob into a special BPF perf event held by + * *map* of type **BPF_MAP_TYPE_PERF_EVENT_ARRAY**. This perf + * event must have the following attributes: **PERF_SAMPLE_RAW** + * as **sample_type**, **PERF_TYPE_SOFTWARE** as **type**, and + * **PERF_COUNT_SW_BPF_OUTPUT** as **config**. + * + * The *flags* are used to indicate the index in *map* for which + * the value must be put, masked with **BPF_F_INDEX_MASK**. + * Alternatively, *flags* can be set to **BPF_F_CURRENT_CPU** + * to indicate that the index of the current CPU core should be + * used. + * + * The value to write, of *size*, is passed through eBPF stack and + * pointed by *data*. + * + * *ctx* is a pointer to in-kernel struct sk_buff. + * + * This helper is similar to **bpf_perf_event_output**\ () but + * restricted to raw_tracepoint bpf programs. + * + * Returns + * 0 on success, or a negative error in case of failure. + */ +static long (*bpf_skb_output)(void *ctx, void *map, __u64 flags, void *data, __u64 size) = (void *) 111; + +/* + * bpf_probe_read_user + * + * Safely attempt to read *size* bytes from user space address + * *unsafe_ptr* and store the data in *dst*. + * + * Returns + * 0 on success, or a negative error in case of failure. + */ +static long (*bpf_probe_read_user)(void *dst, __u32 size, const void *unsafe_ptr) = (void *) 112; + +/* + * bpf_probe_read_kernel + * + * Safely attempt to read *size* bytes from kernel space address + * *unsafe_ptr* and store the data in *dst*. + * + * Returns + * 0 on success, or a negative error in case of failure. + */ +static long (*bpf_probe_read_kernel)(void *dst, __u32 size, const void *unsafe_ptr) = (void *) 113; + +/* + * bpf_probe_read_user_str + * + * Copy a NUL terminated string from an unsafe user address + * *unsafe_ptr* to *dst*. The *size* should include the + * terminating NUL byte. In case the string length is smaller than + * *size*, the target is not padded with further NUL bytes. If the + * string length is larger than *size*, just *size*-1 bytes are + * copied and the last byte is set to NUL. + * + * On success, returns the number of bytes that were written, + * including the terminal NUL. This makes this helper useful in + * tracing programs for reading strings, and more importantly to + * get its length at runtime. See the following snippet: + * + * :: + * + * SEC("kprobe/sys_open") + * void bpf_sys_open(struct pt_regs *ctx) + * { + * char buf[PATHLEN]; // PATHLEN is defined to 256 + * int res = bpf_probe_read_user_str(buf, sizeof(buf), + * ctx->di); + * + * // Consume buf, for example push it to + * // userspace via bpf_perf_event_output(); we + * // can use res (the string length) as event + * // size, after checking its boundaries. + * } + * + * In comparison, using **bpf_probe_read_user**\ () helper here + * instead to read the string would require to estimate the length + * at compile time, and would often result in copying more memory + * than necessary. + * + * Another useful use case is when parsing individual process + * arguments or individual environment variables navigating + * *current*\ **->mm->arg_start** and *current*\ + * **->mm->env_start**: using this helper and the return value, + * one can quickly iterate at the right offset of the memory area. + * + * Returns + * On success, the strictly positive length of the output string, + * including the trailing NUL character. On error, a negative + * value. + */ +static long (*bpf_probe_read_user_str)(void *dst, __u32 size, const void *unsafe_ptr) = (void *) 114; + +/* + * bpf_probe_read_kernel_str + * + * Copy a NUL terminated string from an unsafe kernel address *unsafe_ptr* + * to *dst*. Same semantics as with **bpf_probe_read_user_str**\ () apply. + * + * Returns + * On success, the strictly positive length of the string, including + * the trailing NUL character. On error, a negative value. + */ +static long (*bpf_probe_read_kernel_str)(void *dst, __u32 size, const void *unsafe_ptr) = (void *) 115; + +/* + * bpf_tcp_send_ack + * + * Send out a tcp-ack. *tp* is the in-kernel struct **tcp_sock**. + * *rcv_nxt* is the ack_seq to be sent out. + * + * Returns + * 0 on success, or a negative error in case of failure. + */ +static long (*bpf_tcp_send_ack)(void *tp, __u32 rcv_nxt) = (void *) 116; + +/* + * bpf_send_signal_thread + * + * Send signal *sig* to the thread corresponding to the current task. + * + * Returns + * 0 on success or successfully queued. + * + * **-EBUSY** if work queue under nmi is full. + * + * **-EINVAL** if *sig* is invalid. + * + * **-EPERM** if no permission to send the *sig*. + * + * **-EAGAIN** if bpf program can try again. + */ +static long (*bpf_send_signal_thread)(__u32 sig) = (void *) 117; + +/* + * bpf_jiffies64 + * + * Obtain the 64bit jiffies + * + * Returns + * The 64 bit jiffies + */ +static __u64 (*bpf_jiffies64)(void) = (void *) 118; + +/* + * bpf_read_branch_records + * + * For an eBPF program attached to a perf event, retrieve the + * branch records (**struct perf_branch_entry**) associated to *ctx* + * and store it in the buffer pointed by *buf* up to size + * *size* bytes. + * + * Returns + * On success, number of bytes written to *buf*. On error, a + * negative value. + * + * The *flags* can be set to **BPF_F_GET_BRANCH_RECORDS_SIZE** to + * instead return the number of bytes required to store all the + * branch entries. If this flag is set, *buf* may be NULL. + * + * **-EINVAL** if arguments invalid or **size** not a multiple + * of **sizeof**\ (**struct perf_branch_entry**\ ). + * + * **-ENOENT** if architecture does not support branch records. + */ +static long (*bpf_read_branch_records)(struct bpf_perf_event_data *ctx, void *buf, __u32 size, __u64 flags) = (void *) 119; + +/* + * bpf_get_ns_current_pid_tgid + * + * Returns 0 on success, values for *pid* and *tgid* as seen from the current + * *namespace* will be returned in *nsdata*. + * + * Returns + * 0 on success, or one of the following in case of failure: + * + * **-EINVAL** if dev and inum supplied don't match dev_t and inode number + * with nsfs of current task, or if dev conversion to dev_t lost high bits. + * + * **-ENOENT** if pidns does not exists for the current task. + */ +static long (*bpf_get_ns_current_pid_tgid)(__u64 dev, __u64 ino, struct bpf_pidns_info *nsdata, __u32 size) = (void *) 120; + +/* + * bpf_xdp_output + * + * Write raw *data* blob into a special BPF perf event held by + * *map* of type **BPF_MAP_TYPE_PERF_EVENT_ARRAY**. This perf + * event must have the following attributes: **PERF_SAMPLE_RAW** + * as **sample_type**, **PERF_TYPE_SOFTWARE** as **type**, and + * **PERF_COUNT_SW_BPF_OUTPUT** as **config**. + * + * The *flags* are used to indicate the index in *map* for which + * the value must be put, masked with **BPF_F_INDEX_MASK**. + * Alternatively, *flags* can be set to **BPF_F_CURRENT_CPU** + * to indicate that the index of the current CPU core should be + * used. + * + * The value to write, of *size*, is passed through eBPF stack and + * pointed by *data*. + * + * *ctx* is a pointer to in-kernel struct xdp_buff. + * + * This helper is similar to **bpf_perf_eventoutput**\ () but + * restricted to raw_tracepoint bpf programs. + * + * Returns + * 0 on success, or a negative error in case of failure. + */ +static long (*bpf_xdp_output)(void *ctx, void *map, __u64 flags, void *data, __u64 size) = (void *) 121; + +/* + * bpf_get_netns_cookie + * + * Retrieve the cookie (generated by the kernel) of the network + * namespace the input *ctx* is associated with. The network + * namespace cookie remains stable for its lifetime and provides + * a global identifier that can be assumed unique. If *ctx* is + * NULL, then the helper returns the cookie for the initial + * network namespace. The cookie itself is very similar to that + * of **bpf_get_socket_cookie**\ () helper, but for network + * namespaces instead of sockets. + * + * Returns + * A 8-byte long opaque number. + */ +static __u64 (*bpf_get_netns_cookie)(void *ctx) = (void *) 122; + +/* + * bpf_get_current_ancestor_cgroup_id + * + * Return id of cgroup v2 that is ancestor of the cgroup associated + * with the current task at the *ancestor_level*. The root cgroup + * is at *ancestor_level* zero and each step down the hierarchy + * increments the level. If *ancestor_level* == level of cgroup + * associated with the current task, then return value will be the + * same as that of **bpf_get_current_cgroup_id**\ (). + * + * The helper is useful to implement policies based on cgroups + * that are upper in hierarchy than immediate cgroup associated + * with the current task. + * + * The format of returned id and helper limitations are same as in + * **bpf_get_current_cgroup_id**\ (). + * + * Returns + * The id is returned or 0 in case the id could not be retrieved. + */ +static __u64 (*bpf_get_current_ancestor_cgroup_id)(int ancestor_level) = (void *) 123; + +/* + * bpf_sk_assign + * + * Helper is overloaded depending on BPF program type. This + * description applies to **BPF_PROG_TYPE_SCHED_CLS** and + * **BPF_PROG_TYPE_SCHED_ACT** programs. + * + * Assign the *sk* to the *skb*. When combined with appropriate + * routing configuration to receive the packet towards the socket, + * will cause *skb* to be delivered to the specified socket. + * Subsequent redirection of *skb* via **bpf_redirect**\ (), + * **bpf_clone_redirect**\ () or other methods outside of BPF may + * interfere with successful delivery to the socket. + * + * This operation is only valid from TC ingress path. + * + * The *flags* argument must be zero. + * + * Returns + * 0 on success, or a negative error in case of failure: + * + * **-EINVAL** if specified *flags* are not supported. + * + * **-ENOENT** if the socket is unavailable for assignment. + * + * **-ENETUNREACH** if the socket is unreachable (wrong netns). + * + * **-EOPNOTSUPP** if the operation is not supported, for example + * a call from outside of TC ingress. + * + * **-ESOCKTNOSUPPORT** if the socket type is not supported + * (reuseport). + */ +static long (*bpf_sk_assign)(void *ctx, void *sk, __u64 flags) = (void *) 124; + +/* + * bpf_ktime_get_boot_ns + * + * Return the time elapsed since system boot, in nanoseconds. + * Does include the time the system was suspended. + * See: **clock_gettime**\ (**CLOCK_BOOTTIME**) + * + * Returns + * Current *ktime*. + */ +static __u64 (*bpf_ktime_get_boot_ns)(void) = (void *) 125; + +/* + * bpf_seq_printf + * + * **bpf_seq_printf**\ () uses seq_file **seq_printf**\ () to print + * out the format string. + * The *m* represents the seq_file. The *fmt* and *fmt_size* are for + * the format string itself. The *data* and *data_len* are format string + * arguments. The *data* are a **u64** array and corresponding format string + * values are stored in the array. For strings and pointers where pointees + * are accessed, only the pointer values are stored in the *data* array. + * The *data_len* is the size of *data* in bytes - must be a multiple of 8. + * + * Formats **%s**, **%p{i,I}{4,6}** requires to read kernel memory. + * Reading kernel memory may fail due to either invalid address or + * valid address but requiring a major memory fault. If reading kernel memory + * fails, the string for **%s** will be an empty string, and the ip + * address for **%p{i,I}{4,6}** will be 0. Not returning error to + * bpf program is consistent with what **bpf_trace_printk**\ () does for now. + * + * Returns + * 0 on success, or a negative error in case of failure: + * + * **-EBUSY** if per-CPU memory copy buffer is busy, can try again + * by returning 1 from bpf program. + * + * **-EINVAL** if arguments are invalid, or if *fmt* is invalid/unsupported. + * + * **-E2BIG** if *fmt* contains too many format specifiers. + * + * **-EOVERFLOW** if an overflow happened: The same object will be tried again. + */ +static long (*bpf_seq_printf)(struct seq_file *m, const char *fmt, __u32 fmt_size, const void *data, __u32 data_len) = (void *) 126; + +/* + * bpf_seq_write + * + * **bpf_seq_write**\ () uses seq_file **seq_write**\ () to write the data. + * The *m* represents the seq_file. The *data* and *len* represent the + * data to write in bytes. + * + * Returns + * 0 on success, or a negative error in case of failure: + * + * **-EOVERFLOW** if an overflow happened: The same object will be tried again. + */ +static long (*bpf_seq_write)(struct seq_file *m, const void *data, __u32 len) = (void *) 127; + +/* + * bpf_sk_cgroup_id + * + * Return the cgroup v2 id of the socket *sk*. + * + * *sk* must be a non-**NULL** pointer to a socket, e.g. one + * returned from **bpf_sk_lookup_xxx**\ (), + * **bpf_sk_fullsock**\ (), etc. The format of returned id is + * same as in **bpf_skb_cgroup_id**\ (). + * + * This helper is available only if the kernel was compiled with + * the **CONFIG_SOCK_CGROUP_DATA** configuration option. + * + * Returns + * The id is returned or 0 in case the id could not be retrieved. + */ +static __u64 (*bpf_sk_cgroup_id)(void *sk) = (void *) 128; + +/* + * bpf_sk_ancestor_cgroup_id + * + * Return id of cgroup v2 that is ancestor of cgroup associated + * with the *sk* at the *ancestor_level*. The root cgroup is at + * *ancestor_level* zero and each step down the hierarchy + * increments the level. If *ancestor_level* == level of cgroup + * associated with *sk*, then return value will be same as that + * of **bpf_sk_cgroup_id**\ (). + * + * The helper is useful to implement policies based on cgroups + * that are upper in hierarchy than immediate cgroup associated + * with *sk*. + * + * The format of returned id and helper limitations are same as in + * **bpf_sk_cgroup_id**\ (). + * + * Returns + * The id is returned or 0 in case the id could not be retrieved. + */ +static __u64 (*bpf_sk_ancestor_cgroup_id)(void *sk, int ancestor_level) = (void *) 129; + +/* + * bpf_ringbuf_output + * + * Copy *size* bytes from *data* into a ring buffer *ringbuf*. + * If **BPF_RB_NO_WAKEUP** is specified in *flags*, no notification + * of new data availability is sent. + * If **BPF_RB_FORCE_WAKEUP** is specified in *flags*, notification + * of new data availability is sent unconditionally. + * If **0** is specified in *flags*, an adaptive notification + * of new data availability is sent. + * + * An adaptive notification is a notification sent whenever the user-space + * process has caught up and consumed all available payloads. In case the user-space + * process is still processing a previous payload, then no notification is needed + * as it will process the newly added payload automatically. + * + * Returns + * 0 on success, or a negative error in case of failure. + */ +static long (*bpf_ringbuf_output)(void *ringbuf, void *data, __u64 size, __u64 flags) = (void *) 130; + +/* + * bpf_ringbuf_reserve + * + * Reserve *size* bytes of payload in a ring buffer *ringbuf*. + * *flags* must be 0. + * + * Returns + * Valid pointer with *size* bytes of memory available; NULL, + * otherwise. + */ +static void *(*bpf_ringbuf_reserve)(void *ringbuf, __u64 size, __u64 flags) = (void *) 131; + +/* + * bpf_ringbuf_submit + * + * Submit reserved ring buffer sample, pointed to by *data*. + * If **BPF_RB_NO_WAKEUP** is specified in *flags*, no notification + * of new data availability is sent. + * If **BPF_RB_FORCE_WAKEUP** is specified in *flags*, notification + * of new data availability is sent unconditionally. + * If **0** is specified in *flags*, an adaptive notification + * of new data availability is sent. + * + * See 'bpf_ringbuf_output()' for the definition of adaptive notification. + * + * Returns + * Nothing. Always succeeds. + */ +static void (*bpf_ringbuf_submit)(void *data, __u64 flags) = (void *) 132; + +/* + * bpf_ringbuf_discard + * + * Discard reserved ring buffer sample, pointed to by *data*. + * If **BPF_RB_NO_WAKEUP** is specified in *flags*, no notification + * of new data availability is sent. + * If **BPF_RB_FORCE_WAKEUP** is specified in *flags*, notification + * of new data availability is sent unconditionally. + * If **0** is specified in *flags*, an adaptive notification + * of new data availability is sent. + * + * See 'bpf_ringbuf_output()' for the definition of adaptive notification. + * + * Returns + * Nothing. Always succeeds. + */ +static void (*bpf_ringbuf_discard)(void *data, __u64 flags) = (void *) 133; + +/* + * bpf_ringbuf_query + * + * Query various characteristics of provided ring buffer. What + * exactly is queries is determined by *flags*: + * + * * **BPF_RB_AVAIL_DATA**: Amount of data not yet consumed. + * * **BPF_RB_RING_SIZE**: The size of ring buffer. + * * **BPF_RB_CONS_POS**: Consumer position (can wrap around). + * * **BPF_RB_PROD_POS**: Producer(s) position (can wrap around). + * + * Data returned is just a momentary snapshot of actual values + * and could be inaccurate, so this facility should be used to + * power heuristics and for reporting, not to make 100% correct + * calculation. + * + * Returns + * Requested value, or 0, if *flags* are not recognized. + */ +static __u64 (*bpf_ringbuf_query)(void *ringbuf, __u64 flags) = (void *) 134; + +/* + * bpf_csum_level + * + * Change the skbs checksum level by one layer up or down, or + * reset it entirely to none in order to have the stack perform + * checksum validation. The level is applicable to the following + * protocols: TCP, UDP, GRE, SCTP, FCOE. For example, a decap of + * | ETH | IP | UDP | GUE | IP | TCP | into | ETH | IP | TCP | + * through **bpf_skb_adjust_room**\ () helper with passing in + * **BPF_F_ADJ_ROOM_NO_CSUM_RESET** flag would require one call + * to **bpf_csum_level**\ () with **BPF_CSUM_LEVEL_DEC** since + * the UDP header is removed. Similarly, an encap of the latter + * into the former could be accompanied by a helper call to + * **bpf_csum_level**\ () with **BPF_CSUM_LEVEL_INC** if the + * skb is still intended to be processed in higher layers of the + * stack instead of just egressing at tc. + * + * There are three supported level settings at this time: + * + * * **BPF_CSUM_LEVEL_INC**: Increases skb->csum_level for skbs + * with CHECKSUM_UNNECESSARY. + * * **BPF_CSUM_LEVEL_DEC**: Decreases skb->csum_level for skbs + * with CHECKSUM_UNNECESSARY. + * * **BPF_CSUM_LEVEL_RESET**: Resets skb->csum_level to 0 and + * sets CHECKSUM_NONE to force checksum validation by the stack. + * * **BPF_CSUM_LEVEL_QUERY**: No-op, returns the current + * skb->csum_level. + * + * Returns + * 0 on success, or a negative error in case of failure. In the + * case of **BPF_CSUM_LEVEL_QUERY**, the current skb->csum_level + * is returned or the error code -EACCES in case the skb is not + * subject to CHECKSUM_UNNECESSARY. + */ +static long (*bpf_csum_level)(struct __sk_buff *skb, __u64 level) = (void *) 135; + +/* + * bpf_skc_to_tcp6_sock + * + * Dynamically cast a *sk* pointer to a *tcp6_sock* pointer. + * + * Returns + * *sk* if casting is valid, or **NULL** otherwise. + */ +static struct tcp6_sock *(*bpf_skc_to_tcp6_sock)(void *sk) = (void *) 136; + +/* + * bpf_skc_to_tcp_sock + * + * Dynamically cast a *sk* pointer to a *tcp_sock* pointer. + * + * Returns + * *sk* if casting is valid, or **NULL** otherwise. + */ +static struct tcp_sock *(*bpf_skc_to_tcp_sock)(void *sk) = (void *) 137; + +/* + * bpf_skc_to_tcp_timewait_sock + * + * Dynamically cast a *sk* pointer to a *tcp_timewait_sock* pointer. + * + * Returns + * *sk* if casting is valid, or **NULL** otherwise. + */ +static struct tcp_timewait_sock *(*bpf_skc_to_tcp_timewait_sock)(void *sk) = (void *) 138; + +/* + * bpf_skc_to_tcp_request_sock + * + * Dynamically cast a *sk* pointer to a *tcp_request_sock* pointer. + * + * Returns + * *sk* if casting is valid, or **NULL** otherwise. + */ +static struct tcp_request_sock *(*bpf_skc_to_tcp_request_sock)(void *sk) = (void *) 139; + +/* + * bpf_skc_to_udp6_sock + * + * Dynamically cast a *sk* pointer to a *udp6_sock* pointer. + * + * Returns + * *sk* if casting is valid, or **NULL** otherwise. + */ +static struct udp6_sock *(*bpf_skc_to_udp6_sock)(void *sk) = (void *) 140; + +/* + * bpf_get_task_stack + * + * Return a user or a kernel stack in bpf program provided buffer. + * To achieve this, the helper needs *task*, which is a valid + * pointer to **struct task_struct**. To store the stacktrace, the + * bpf program provides *buf* with a nonnegative *size*. + * + * The last argument, *flags*, holds the number of stack frames to + * skip (from 0 to 255), masked with + * **BPF_F_SKIP_FIELD_MASK**. The next bits can be used to set + * the following flags: + * + * **BPF_F_USER_STACK** + * Collect a user space stack instead of a kernel stack. + * **BPF_F_USER_BUILD_ID** + * Collect buildid+offset instead of ips for user stack, + * only valid if **BPF_F_USER_STACK** is also specified. + * + * **bpf_get_task_stack**\ () can collect up to + * **PERF_MAX_STACK_DEPTH** both kernel and user frames, subject + * to sufficient large buffer size. Note that + * this limit can be controlled with the **sysctl** program, and + * that it should be manually increased in order to profile long + * user stacks (such as stacks for Java programs). To do so, use: + * + * :: + * + * # sysctl kernel.perf_event_max_stack= + * + * Returns + * A non-negative value equal to or less than *size* on success, + * or a negative error in case of failure. + */ +static long (*bpf_get_task_stack)(struct task_struct *task, void *buf, __u32 size, __u64 flags) = (void *) 141; + +/* + * bpf_load_hdr_opt + * + * Load header option. Support reading a particular TCP header + * option for bpf program (**BPF_PROG_TYPE_SOCK_OPS**). + * + * If *flags* is 0, it will search the option from the + * *skops*\ **->skb_data**. The comment in **struct bpf_sock_ops** + * has details on what skb_data contains under different + * *skops*\ **->op**. + * + * The first byte of the *searchby_res* specifies the + * kind that it wants to search. + * + * If the searching kind is an experimental kind + * (i.e. 253 or 254 according to RFC6994). It also + * needs to specify the "magic" which is either + * 2 bytes or 4 bytes. It then also needs to + * specify the size of the magic by using + * the 2nd byte which is "kind-length" of a TCP + * header option and the "kind-length" also + * includes the first 2 bytes "kind" and "kind-length" + * itself as a normal TCP header option also does. + * + * For example, to search experimental kind 254 with + * 2 byte magic 0xeB9F, the searchby_res should be + * [ 254, 4, 0xeB, 0x9F, 0, 0, .... 0 ]. + * + * To search for the standard window scale option (3), + * the *searchby_res* should be [ 3, 0, 0, .... 0 ]. + * Note, kind-length must be 0 for regular option. + * + * Searching for No-Op (0) and End-of-Option-List (1) are + * not supported. + * + * *len* must be at least 2 bytes which is the minimal size + * of a header option. + * + * Supported flags: + * + * * **BPF_LOAD_HDR_OPT_TCP_SYN** to search from the + * saved_syn packet or the just-received syn packet. + * + * + * Returns + * > 0 when found, the header option is copied to *searchby_res*. + * The return value is the total length copied. On failure, a + * negative error code is returned: + * + * **-EINVAL** if a parameter is invalid. + * + * **-ENOMSG** if the option is not found. + * + * **-ENOENT** if no syn packet is available when + * **BPF_LOAD_HDR_OPT_TCP_SYN** is used. + * + * **-ENOSPC** if there is not enough space. Only *len* number of + * bytes are copied. + * + * **-EFAULT** on failure to parse the header options in the + * packet. + * + * **-EPERM** if the helper cannot be used under the current + * *skops*\ **->op**. + */ +static long (*bpf_load_hdr_opt)(struct bpf_sock_ops *skops, void *searchby_res, __u32 len, __u64 flags) = (void *) 142; + +/* + * bpf_store_hdr_opt + * + * Store header option. The data will be copied + * from buffer *from* with length *len* to the TCP header. + * + * The buffer *from* should have the whole option that + * includes the kind, kind-length, and the actual + * option data. The *len* must be at least kind-length + * long. The kind-length does not have to be 4 byte + * aligned. The kernel will take care of the padding + * and setting the 4 bytes aligned value to th->doff. + * + * This helper will check for duplicated option + * by searching the same option in the outgoing skb. + * + * This helper can only be called during + * **BPF_SOCK_OPS_WRITE_HDR_OPT_CB**. + * + * + * Returns + * 0 on success, or negative error in case of failure: + * + * **-EINVAL** If param is invalid. + * + * **-ENOSPC** if there is not enough space in the header. + * Nothing has been written + * + * **-EEXIST** if the option already exists. + * + * **-EFAULT** on failrue to parse the existing header options. + * + * **-EPERM** if the helper cannot be used under the current + * *skops*\ **->op**. + */ +static long (*bpf_store_hdr_opt)(struct bpf_sock_ops *skops, const void *from, __u32 len, __u64 flags) = (void *) 143; + +/* + * bpf_reserve_hdr_opt + * + * Reserve *len* bytes for the bpf header option. The + * space will be used by **bpf_store_hdr_opt**\ () later in + * **BPF_SOCK_OPS_WRITE_HDR_OPT_CB**. + * + * If **bpf_reserve_hdr_opt**\ () is called multiple times, + * the total number of bytes will be reserved. + * + * This helper can only be called during + * **BPF_SOCK_OPS_HDR_OPT_LEN_CB**. + * + * + * Returns + * 0 on success, or negative error in case of failure: + * + * **-EINVAL** if a parameter is invalid. + * + * **-ENOSPC** if there is not enough space in the header. + * + * **-EPERM** if the helper cannot be used under the current + * *skops*\ **->op**. + */ +static long (*bpf_reserve_hdr_opt)(struct bpf_sock_ops *skops, __u32 len, __u64 flags) = (void *) 144; + +/* + * bpf_inode_storage_get + * + * Get a bpf_local_storage from an *inode*. + * + * Logically, it could be thought of as getting the value from + * a *map* with *inode* as the **key**. From this + * perspective, the usage is not much different from + * **bpf_map_lookup_elem**\ (*map*, **&**\ *inode*) except this + * helper enforces the key must be an inode and the map must also + * be a **BPF_MAP_TYPE_INODE_STORAGE**. + * + * Underneath, the value is stored locally at *inode* instead of + * the *map*. The *map* is used as the bpf-local-storage + * "type". The bpf-local-storage "type" (i.e. the *map*) is + * searched against all bpf_local_storage residing at *inode*. + * + * An optional *flags* (**BPF_LOCAL_STORAGE_GET_F_CREATE**) can be + * used such that a new bpf_local_storage will be + * created if one does not exist. *value* can be used + * together with **BPF_LOCAL_STORAGE_GET_F_CREATE** to specify + * the initial value of a bpf_local_storage. If *value* is + * **NULL**, the new bpf_local_storage will be zero initialized. + * + * Returns + * A bpf_local_storage pointer is returned on success. + * + * **NULL** if not found or there was an error in adding + * a new bpf_local_storage. + */ +static void *(*bpf_inode_storage_get)(void *map, void *inode, void *value, __u64 flags) = (void *) 145; + +/* + * bpf_inode_storage_delete + * + * Delete a bpf_local_storage from an *inode*. + * + * Returns + * 0 on success. + * + * **-ENOENT** if the bpf_local_storage cannot be found. + */ +static int (*bpf_inode_storage_delete)(void *map, void *inode) = (void *) 146; + +/* + * bpf_d_path + * + * Return full path for given **struct path** object, which + * needs to be the kernel BTF *path* object. The path is + * returned in the provided buffer *buf* of size *sz* and + * is zero terminated. + * + * + * Returns + * On success, the strictly positive length of the string, + * including the trailing NUL character. On error, a negative + * value. + */ +static long (*bpf_d_path)(struct path *path, char *buf, __u32 sz) = (void *) 147; + +/* + * bpf_copy_from_user + * + * Read *size* bytes from user space address *user_ptr* and store + * the data in *dst*. This is a wrapper of **copy_from_user**\ (). + * + * Returns + * 0 on success, or a negative error in case of failure. + */ +static long (*bpf_copy_from_user)(void *dst, __u32 size, const void *user_ptr) = (void *) 148; + +/* + * bpf_snprintf_btf + * + * Use BTF to store a string representation of *ptr*->ptr in *str*, + * using *ptr*->type_id. This value should specify the type + * that *ptr*->ptr points to. LLVM __builtin_btf_type_id(type, 1) + * can be used to look up vmlinux BTF type ids. Traversing the + * data structure using BTF, the type information and values are + * stored in the first *str_size* - 1 bytes of *str*. Safe copy of + * the pointer data is carried out to avoid kernel crashes during + * operation. Smaller types can use string space on the stack; + * larger programs can use map data to store the string + * representation. + * + * The string can be subsequently shared with userspace via + * bpf_perf_event_output() or ring buffer interfaces. + * bpf_trace_printk() is to be avoided as it places too small + * a limit on string size to be useful. + * + * *flags* is a combination of + * + * **BTF_F_COMPACT** + * no formatting around type information + * **BTF_F_NONAME** + * no struct/union member names/types + * **BTF_F_PTR_RAW** + * show raw (unobfuscated) pointer values; + * equivalent to printk specifier %px. + * **BTF_F_ZERO** + * show zero-valued struct/union members; they + * are not displayed by default + * + * + * Returns + * The number of bytes that were written (or would have been + * written if output had to be truncated due to string size), + * or a negative error in cases of failure. + */ +static long (*bpf_snprintf_btf)(char *str, __u32 str_size, struct btf_ptr *ptr, __u32 btf_ptr_size, __u64 flags) = (void *) 149; + +/* + * bpf_seq_printf_btf + * + * Use BTF to write to seq_write a string representation of + * *ptr*->ptr, using *ptr*->type_id as per bpf_snprintf_btf(). + * *flags* are identical to those used for bpf_snprintf_btf. + * + * Returns + * 0 on success or a negative error in case of failure. + */ +static long (*bpf_seq_printf_btf)(struct seq_file *m, struct btf_ptr *ptr, __u32 ptr_size, __u64 flags) = (void *) 150; + +/* + * bpf_skb_cgroup_classid + * + * See **bpf_get_cgroup_classid**\ () for the main description. + * This helper differs from **bpf_get_cgroup_classid**\ () in that + * the cgroup v1 net_cls class is retrieved only from the *skb*'s + * associated socket instead of the current process. + * + * Returns + * The id is returned or 0 in case the id could not be retrieved. + */ +static __u64 (*bpf_skb_cgroup_classid)(struct __sk_buff *skb) = (void *) 151; + +/* + * bpf_redirect_neigh + * + * Redirect the packet to another net device of index *ifindex* + * and fill in L2 addresses from neighboring subsystem. This helper + * is somewhat similar to **bpf_redirect**\ (), except that it + * populates L2 addresses as well, meaning, internally, the helper + * relies on the neighbor lookup for the L2 address of the nexthop. + * + * The helper will perform a FIB lookup based on the skb's + * networking header to get the address of the next hop, unless + * this is supplied by the caller in the *params* argument. The + * *plen* argument indicates the len of *params* and should be set + * to 0 if *params* is NULL. + * + * The *flags* argument is reserved and must be 0. The helper is + * currently only supported for tc BPF program types, and enabled + * for IPv4 and IPv6 protocols. + * + * Returns + * The helper returns **TC_ACT_REDIRECT** on success or + * **TC_ACT_SHOT** on error. + */ +static long (*bpf_redirect_neigh)(__u32 ifindex, struct bpf_redir_neigh *params, int plen, __u64 flags) = (void *) 152; + +/* + * bpf_per_cpu_ptr + * + * Take a pointer to a percpu ksym, *percpu_ptr*, and return a + * pointer to the percpu kernel variable on *cpu*. A ksym is an + * extern variable decorated with '__ksym'. For ksym, there is a + * global var (either static or global) defined of the same name + * in the kernel. The ksym is percpu if the global var is percpu. + * The returned pointer points to the global percpu var on *cpu*. + * + * bpf_per_cpu_ptr() has the same semantic as per_cpu_ptr() in the + * kernel, except that bpf_per_cpu_ptr() may return NULL. This + * happens if *cpu* is larger than nr_cpu_ids. The caller of + * bpf_per_cpu_ptr() must check the returned value. + * + * Returns + * A pointer pointing to the kernel percpu variable on *cpu*, or + * NULL, if *cpu* is invalid. + */ +static void *(*bpf_per_cpu_ptr)(const void *percpu_ptr, __u32 cpu) = (void *) 153; + +/* + * bpf_this_cpu_ptr + * + * Take a pointer to a percpu ksym, *percpu_ptr*, and return a + * pointer to the percpu kernel variable on this cpu. See the + * description of 'ksym' in **bpf_per_cpu_ptr**\ (). + * + * bpf_this_cpu_ptr() has the same semantic as this_cpu_ptr() in + * the kernel. Different from **bpf_per_cpu_ptr**\ (), it would + * never return NULL. + * + * Returns + * A pointer pointing to the kernel percpu variable on this cpu. + */ +static void *(*bpf_this_cpu_ptr)(const void *percpu_ptr) = (void *) 154; + +/* + * bpf_redirect_peer + * + * Redirect the packet to another net device of index *ifindex*. + * This helper is somewhat similar to **bpf_redirect**\ (), except + * that the redirection happens to the *ifindex*' peer device and + * the netns switch takes place from ingress to ingress without + * going through the CPU's backlog queue. + * + * The *flags* argument is reserved and must be 0. The helper is + * currently only supported for tc BPF program types at the ingress + * hook and for veth device types. The peer device must reside in a + * different network namespace. + * + * Returns + * The helper returns **TC_ACT_REDIRECT** on success or + * **TC_ACT_SHOT** on error. + */ +static long (*bpf_redirect_peer)(__u32 ifindex, __u64 flags) = (void *) 155; + +/* + * bpf_task_storage_get + * + * Get a bpf_local_storage from the *task*. + * + * Logically, it could be thought of as getting the value from + * a *map* with *task* as the **key**. From this + * perspective, the usage is not much different from + * **bpf_map_lookup_elem**\ (*map*, **&**\ *task*) except this + * helper enforces the key must be an task_struct and the map must also + * be a **BPF_MAP_TYPE_TASK_STORAGE**. + * + * Underneath, the value is stored locally at *task* instead of + * the *map*. The *map* is used as the bpf-local-storage + * "type". The bpf-local-storage "type" (i.e. the *map*) is + * searched against all bpf_local_storage residing at *task*. + * + * An optional *flags* (**BPF_LOCAL_STORAGE_GET_F_CREATE**) can be + * used such that a new bpf_local_storage will be + * created if one does not exist. *value* can be used + * together with **BPF_LOCAL_STORAGE_GET_F_CREATE** to specify + * the initial value of a bpf_local_storage. If *value* is + * **NULL**, the new bpf_local_storage will be zero initialized. + * + * Returns + * A bpf_local_storage pointer is returned on success. + * + * **NULL** if not found or there was an error in adding + * a new bpf_local_storage. + */ +static void *(*bpf_task_storage_get)(void *map, struct task_struct *task, void *value, __u64 flags) = (void *) 156; + +/* + * bpf_task_storage_delete + * + * Delete a bpf_local_storage from a *task*. + * + * Returns + * 0 on success. + * + * **-ENOENT** if the bpf_local_storage cannot be found. + */ +static long (*bpf_task_storage_delete)(void *map, struct task_struct *task) = (void *) 157; + +/* + * bpf_get_current_task_btf + * + * Return a BTF pointer to the "current" task. + * This pointer can also be used in helpers that accept an + * *ARG_PTR_TO_BTF_ID* of type *task_struct*. + * + * Returns + * Pointer to the current task. + */ +static struct task_struct *(*bpf_get_current_task_btf)(void) = (void *) 158; + +/* + * bpf_bprm_opts_set + * + * Set or clear certain options on *bprm*: + * + * **BPF_F_BPRM_SECUREEXEC** Set the secureexec bit + * which sets the **AT_SECURE** auxv for glibc. The bit + * is cleared if the flag is not specified. + * + * Returns + * **-EINVAL** if invalid *flags* are passed, zero otherwise. + */ +static long (*bpf_bprm_opts_set)(struct linux_binprm *bprm, __u64 flags) = (void *) 159; + +/* + * bpf_ktime_get_coarse_ns + * + * Return a coarse-grained version of the time elapsed since + * system boot, in nanoseconds. Does not include time the system + * was suspended. + * + * See: **clock_gettime**\ (**CLOCK_MONOTONIC_COARSE**) + * + * Returns + * Current *ktime*. + */ +static __u64 (*bpf_ktime_get_coarse_ns)(void) = (void *) 160; + +/* + * bpf_ima_inode_hash + * + * Returns the stored IMA hash of the *inode* (if it's avaialable). + * If the hash is larger than *size*, then only *size* + * bytes will be copied to *dst* + * + * Returns + * The **hash_algo** is returned on success, + * **-EOPNOTSUP** if IMA is disabled or **-EINVAL** if + * invalid arguments are passed. + */ +static long (*bpf_ima_inode_hash)(struct inode *inode, void *dst, __u32 size) = (void *) 161; + +/* + * bpf_sock_from_file + * + * If the given file represents a socket, returns the associated + * socket. + * + * Returns + * A pointer to a struct socket on success or NULL if the file is + * not a socket. + */ +static struct socket *(*bpf_sock_from_file)(struct file *file) = (void *) 162; + +/* + * bpf_check_mtu + * + * Check packet size against exceeding MTU of net device (based + * on *ifindex*). This helper will likely be used in combination + * with helpers that adjust/change the packet size. + * + * The argument *len_diff* can be used for querying with a planned + * size change. This allows to check MTU prior to changing packet + * ctx. Providing an *len_diff* adjustment that is larger than the + * actual packet size (resulting in negative packet size) will in + * principle not exceed the MTU, why it is not considered a + * failure. Other BPF-helpers are needed for performing the + * planned size change, why the responsibility for catch a negative + * packet size belong in those helpers. + * + * Specifying *ifindex* zero means the MTU check is performed + * against the current net device. This is practical if this isn't + * used prior to redirect. + * + * On input *mtu_len* must be a valid pointer, else verifier will + * reject BPF program. If the value *mtu_len* is initialized to + * zero then the ctx packet size is use. When value *mtu_len* is + * provided as input this specify the L3 length that the MTU check + * is done against. Remember XDP and TC length operate at L2, but + * this value is L3 as this correlate to MTU and IP-header tot_len + * values which are L3 (similar behavior as bpf_fib_lookup). + * + * The Linux kernel route table can configure MTUs on a more + * specific per route level, which is not provided by this helper. + * For route level MTU checks use the **bpf_fib_lookup**\ () + * helper. + * + * *ctx* is either **struct xdp_md** for XDP programs or + * **struct sk_buff** for tc cls_act programs. + * + * The *flags* argument can be a combination of one or more of the + * following values: + * + * **BPF_MTU_CHK_SEGS** + * This flag will only works for *ctx* **struct sk_buff**. + * If packet context contains extra packet segment buffers + * (often knows as GSO skb), then MTU check is harder to + * check at this point, because in transmit path it is + * possible for the skb packet to get re-segmented + * (depending on net device features). This could still be + * a MTU violation, so this flag enables performing MTU + * check against segments, with a different violation + * return code to tell it apart. Check cannot use len_diff. + * + * On return *mtu_len* pointer contains the MTU value of the net + * device. Remember the net device configured MTU is the L3 size, + * which is returned here and XDP and TC length operate at L2. + * Helper take this into account for you, but remember when using + * MTU value in your BPF-code. + * + * + * Returns + * * 0 on success, and populate MTU value in *mtu_len* pointer. + * + * * < 0 if any input argument is invalid (*mtu_len* not updated) + * + * MTU violations return positive values, but also populate MTU + * value in *mtu_len* pointer, as this can be needed for + * implementing PMTU handing: + * + * * **BPF_MTU_CHK_RET_FRAG_NEEDED** + * * **BPF_MTU_CHK_RET_SEGS_TOOBIG** + */ +static long (*bpf_check_mtu)(void *ctx, __u32 ifindex, __u32 *mtu_len, __s32 len_diff, __u64 flags) = (void *) 163; + +/* + * bpf_for_each_map_elem + * + * For each element in **map**, call **callback_fn** function with + * **map**, **callback_ctx** and other map-specific parameters. + * The **callback_fn** should be a static function and + * the **callback_ctx** should be a pointer to the stack. + * The **flags** is used to control certain aspects of the helper. + * Currently, the **flags** must be 0. + * + * The following are a list of supported map types and their + * respective expected callback signatures: + * + * BPF_MAP_TYPE_HASH, BPF_MAP_TYPE_PERCPU_HASH, + * BPF_MAP_TYPE_LRU_HASH, BPF_MAP_TYPE_LRU_PERCPU_HASH, + * BPF_MAP_TYPE_ARRAY, BPF_MAP_TYPE_PERCPU_ARRAY + * + * long (\*callback_fn)(struct bpf_map \*map, const void \*key, void \*value, void \*ctx); + * + * For per_cpu maps, the map_value is the value on the cpu where the + * bpf_prog is running. + * + * If **callback_fn** return 0, the helper will continue to the next + * element. If return value is 1, the helper will skip the rest of + * elements and return. Other return values are not used now. + * + * + * Returns + * The number of traversed map elements for success, **-EINVAL** for + * invalid **flags**. + */ +static long (*bpf_for_each_map_elem)(void *map, void *callback_fn, void *callback_ctx, __u64 flags) = (void *) 164; + +/* + * bpf_snprintf + * + * Outputs a string into the **str** buffer of size **str_size** + * based on a format string stored in a read-only map pointed by + * **fmt**. + * + * Each format specifier in **fmt** corresponds to one u64 element + * in the **data** array. For strings and pointers where pointees + * are accessed, only the pointer values are stored in the *data* + * array. The *data_len* is the size of *data* in bytes - must be + * a multiple of 8. + * + * Formats **%s** and **%p{i,I}{4,6}** require to read kernel + * memory. Reading kernel memory may fail due to either invalid + * address or valid address but requiring a major memory fault. If + * reading kernel memory fails, the string for **%s** will be an + * empty string, and the ip address for **%p{i,I}{4,6}** will be 0. + * Not returning error to bpf program is consistent with what + * **bpf_trace_printk**\ () does for now. + * + * + * Returns + * The strictly positive length of the formatted string, including + * the trailing zero character. If the return value is greater than + * **str_size**, **str** contains a truncated string, guaranteed to + * be zero-terminated except when **str_size** is 0. + * + * Or **-EBUSY** if the per-CPU memory copy buffer is busy. + */ +static long (*bpf_snprintf)(char *str, __u32 str_size, const char *fmt, __u64 *data, __u32 data_len) = (void *) 165; + +/* + * bpf_sys_bpf + * + * Execute bpf syscall with given arguments. + * + * Returns + * A syscall result. + */ +static long (*bpf_sys_bpf)(__u32 cmd, void *attr, __u32 attr_size) = (void *) 166; + +/* + * bpf_btf_find_by_name_kind + * + * Find BTF type with given name and kind in vmlinux BTF or in module's BTFs. + * + * Returns + * Returns btf_id and btf_obj_fd in lower and upper 32 bits. + */ +static long (*bpf_btf_find_by_name_kind)(char *name, int name_sz, __u32 kind, int flags) = (void *) 167; + +/* + * bpf_sys_close + * + * Execute close syscall for given FD. + * + * Returns + * A syscall result. + */ +static long (*bpf_sys_close)(__u32 fd) = (void *) 168; + +/* + * bpf_timer_init + * + * Initialize the timer. + * First 4 bits of *flags* specify clockid. + * Only CLOCK_MONOTONIC, CLOCK_REALTIME, CLOCK_BOOTTIME are allowed. + * All other bits of *flags* are reserved. + * The verifier will reject the program if *timer* is not from + * the same *map*. + * + * Returns + * 0 on success. + * **-EBUSY** if *timer* is already initialized. + * **-EINVAL** if invalid *flags* are passed. + * **-EPERM** if *timer* is in a map that doesn't have any user references. + * The user space should either hold a file descriptor to a map with timers + * or pin such map in bpffs. When map is unpinned or file descriptor is + * closed all timers in the map will be cancelled and freed. + */ +static long (*bpf_timer_init)(struct bpf_timer *timer, void *map, __u64 flags) = (void *) 169; + +/* + * bpf_timer_set_callback + * + * Configure the timer to call *callback_fn* static function. + * + * Returns + * 0 on success. + * **-EINVAL** if *timer* was not initialized with bpf_timer_init() earlier. + * **-EPERM** if *timer* is in a map that doesn't have any user references. + * The user space should either hold a file descriptor to a map with timers + * or pin such map in bpffs. When map is unpinned or file descriptor is + * closed all timers in the map will be cancelled and freed. + */ +static long (*bpf_timer_set_callback)(struct bpf_timer *timer, void *callback_fn) = (void *) 170; + +/* + * bpf_timer_start + * + * Set timer expiration N nanoseconds from the current time. The + * configured callback will be invoked in soft irq context on some cpu + * and will not repeat unless another bpf_timer_start() is made. + * In such case the next invocation can migrate to a different cpu. + * Since struct bpf_timer is a field inside map element the map + * owns the timer. The bpf_timer_set_callback() will increment refcnt + * of BPF program to make sure that callback_fn code stays valid. + * When user space reference to a map reaches zero all timers + * in a map are cancelled and corresponding program's refcnts are + * decremented. This is done to make sure that Ctrl-C of a user + * process doesn't leave any timers running. If map is pinned in + * bpffs the callback_fn can re-arm itself indefinitely. + * bpf_map_update/delete_elem() helpers and user space sys_bpf commands + * cancel and free the timer in the given map element. + * The map can contain timers that invoke callback_fn-s from different + * programs. The same callback_fn can serve different timers from + * different maps if key/value layout matches across maps. + * Every bpf_timer_set_callback() can have different callback_fn. + * + * + * Returns + * 0 on success. + * **-EINVAL** if *timer* was not initialized with bpf_timer_init() earlier + * or invalid *flags* are passed. + */ +static long (*bpf_timer_start)(struct bpf_timer *timer, __u64 nsecs, __u64 flags) = (void *) 171; + +/* + * bpf_timer_cancel + * + * Cancel the timer and wait for callback_fn to finish if it was running. + * + * Returns + * 0 if the timer was not active. + * 1 if the timer was active. + * **-EINVAL** if *timer* was not initialized with bpf_timer_init() earlier. + * **-EDEADLK** if callback_fn tried to call bpf_timer_cancel() on its + * own timer which would have led to a deadlock otherwise. + */ +static long (*bpf_timer_cancel)(struct bpf_timer *timer) = (void *) 172; + +/* + * bpf_get_func_ip + * + * Get address of the traced function (for tracing and kprobe programs). + * + * Returns + * Address of the traced function. + */ +static __u64 (*bpf_get_func_ip)(void *ctx) = (void *) 173; + +/* + * bpf_get_attach_cookie + * + * Get bpf_cookie value provided (optionally) during the program + * attachment. It might be different for each individual + * attachment, even if BPF program itself is the same. + * Expects BPF program context *ctx* as a first argument. + * + * Supported for the following program types: + * - kprobe/uprobe; + * - tracepoint; + * - perf_event. + * + * Returns + * Value specified by user at BPF link creation/attachment time + * or 0, if it was not specified. + */ +static __u64 (*bpf_get_attach_cookie)(void *ctx) = (void *) 174; + +/* + * bpf_task_pt_regs + * + * Get the struct pt_regs associated with **task**. + * + * Returns + * A pointer to struct pt_regs. + */ +static long (*bpf_task_pt_regs)(struct task_struct *task) = (void *) 175; + +/* + * bpf_get_branch_snapshot + * + * Get branch trace from hardware engines like Intel LBR. The + * hardware engine is stopped shortly after the helper is + * called. Therefore, the user need to filter branch entries + * based on the actual use case. To capture branch trace + * before the trigger point of the BPF program, the helper + * should be called at the beginning of the BPF program. + * + * The data is stored as struct perf_branch_entry into output + * buffer *entries*. *size* is the size of *entries* in bytes. + * *flags* is reserved for now and must be zero. + * + * + * Returns + * On success, number of bytes written to *buf*. On error, a + * negative value. + * + * **-EINVAL** if *flags* is not zero. + * + * **-ENOENT** if architecture does not support branch records. + */ +static long (*bpf_get_branch_snapshot)(void *entries, __u32 size, __u64 flags) = (void *) 176; + +/* + * bpf_trace_vprintk + * + * Behaves like **bpf_trace_printk**\ () helper, but takes an array of u64 + * to format and can handle more format args as a result. + * + * Arguments are to be used as in **bpf_seq_printf**\ () helper. + * + * Returns + * The number of bytes written to the buffer, or a negative error + * in case of failure. + */ +static long (*bpf_trace_vprintk)(const char *fmt, __u32 fmt_size, const void *data, __u32 data_len) = (void *) 177; + +/* + * bpf_skc_to_unix_sock + * + * Dynamically cast a *sk* pointer to a *unix_sock* pointer. + * + * Returns + * *sk* if casting is valid, or **NULL** otherwise. + */ +static struct unix_sock *(*bpf_skc_to_unix_sock)(void *sk) = (void *) 178; + +/* + * bpf_kallsyms_lookup_name + * + * Get the address of a kernel symbol, returned in *res*. *res* is + * set to 0 if the symbol is not found. + * + * Returns + * On success, zero. On error, a negative value. + * + * **-EINVAL** if *flags* is not zero. + * + * **-EINVAL** if string *name* is not the same size as *name_sz*. + * + * **-ENOENT** if symbol is not found. + * + * **-EPERM** if caller does not have permission to obtain kernel address. + */ +static long (*bpf_kallsyms_lookup_name)(const char *name, int name_sz, int flags, __u64 *res) = (void *) 179; + +/* + * bpf_find_vma + * + * Find vma of *task* that contains *addr*, call *callback_fn* + * function with *task*, *vma*, and *callback_ctx*. + * The *callback_fn* should be a static function and + * the *callback_ctx* should be a pointer to the stack. + * The *flags* is used to control certain aspects of the helper. + * Currently, the *flags* must be 0. + * + * The expected callback signature is + * + * long (\*callback_fn)(struct task_struct \*task, struct vm_area_struct \*vma, void \*callback_ctx); + * + * + * Returns + * 0 on success. + * **-ENOENT** if *task->mm* is NULL, or no vma contains *addr*. + * **-EBUSY** if failed to try lock mmap_lock. + * **-EINVAL** for invalid **flags**. + */ +static long (*bpf_find_vma)(struct task_struct *task, __u64 addr, void *callback_fn, void *callback_ctx, __u64 flags) = (void *) 180; + + diff --git a/internal/ebpf/spike/c/bpf_helpers.h b/internal/ebpf/spike/c/bpf_helpers.h new file mode 100644 index 000000000..963b1060d --- /dev/null +++ b/internal/ebpf/spike/c/bpf_helpers.h @@ -0,0 +1,262 @@ +/* SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause) */ +#ifndef __BPF_HELPERS__ +#define __BPF_HELPERS__ + +/* + * Note that bpf programs need to include either + * vmlinux.h (auto-generated from BTF) or linux/types.h + * in advance since bpf_helper_defs.h uses such types + * as __u64. + */ +#include "bpf_helper_defs.h" + +#define __uint(name, val) int (*name)[val] +#define __type(name, val) typeof(val) *name +#define __array(name, val) typeof(val) *name[] + +/* + * Helper macro to place programs, maps, license in + * different sections in elf_bpf file. Section names + * are interpreted by libbpf depending on the context (BPF programs, BPF maps, + * extern variables, etc). + * To allow use of SEC() with externs (e.g., for extern .maps declarations), + * make sure __attribute__((unused)) doesn't trigger compilation warning. + */ +#define SEC(name) \ + _Pragma("GCC diagnostic push") \ + _Pragma("GCC diagnostic ignored \"-Wignored-attributes\"") \ + __attribute__((section(name), used)) \ + _Pragma("GCC diagnostic pop") \ + +/* Avoid 'linux/stddef.h' definition of '__always_inline'. */ +#undef __always_inline +#define __always_inline inline __attribute__((always_inline)) + +#ifndef __noinline +#define __noinline __attribute__((noinline)) +#endif +#ifndef __weak +#define __weak __attribute__((weak)) +#endif + +/* + * Use __hidden attribute to mark a non-static BPF subprogram effectively + * static for BPF verifier's verification algorithm purposes, allowing more + * extensive and permissive BPF verification process, taking into account + * subprogram's caller context. + */ +#define __hidden __attribute__((visibility("hidden"))) + +/* When utilizing vmlinux.h with BPF CO-RE, user BPF programs can't include + * any system-level headers (such as stddef.h, linux/version.h, etc), and + * commonly-used macros like NULL and KERNEL_VERSION aren't available through + * vmlinux.h. This just adds unnecessary hurdles and forces users to re-define + * them on their own. So as a convenience, provide such definitions here. + */ +#ifndef NULL +#define NULL ((void *)0) +#endif + +#ifndef KERNEL_VERSION +#define KERNEL_VERSION(a, b, c) (((a) << 16) + ((b) << 8) + ((c) > 255 ? 255 : (c))) +#endif + +/* + * Helper macros to manipulate data structures + */ +#ifndef offsetof +#define offsetof(TYPE, MEMBER) ((unsigned long)&((TYPE *)0)->MEMBER) +#endif +#ifndef container_of +#define container_of(ptr, type, member) \ + ({ \ + void *__mptr = (void *)(ptr); \ + ((type *)(__mptr - offsetof(type, member))); \ + }) +#endif + +/* + * Helper macro to throw a compilation error if __bpf_unreachable() gets + * built into the resulting code. This works given BPF back end does not + * implement __builtin_trap(). This is useful to assert that certain paths + * of the program code are never used and hence eliminated by the compiler. + * + * For example, consider a switch statement that covers known cases used by + * the program. __bpf_unreachable() can then reside in the default case. If + * the program gets extended such that a case is not covered in the switch + * statement, then it will throw a build error due to the default case not + * being compiled out. + */ +#ifndef __bpf_unreachable +# define __bpf_unreachable() __builtin_trap() +#endif + +/* + * Helper function to perform a tail call with a constant/immediate map slot. + */ +#if __clang_major__ >= 8 && defined(__bpf__) +static __always_inline void +bpf_tail_call_static(void *ctx, const void *map, const __u32 slot) +{ + if (!__builtin_constant_p(slot)) + __bpf_unreachable(); + + /* + * Provide a hard guarantee that LLVM won't optimize setting r2 (map + * pointer) and r3 (constant map index) from _different paths_ ending + * up at the _same_ call insn as otherwise we won't be able to use the + * jmpq/nopl retpoline-free patching by the x86-64 JIT in the kernel + * given they mismatch. See also d2e4c1e6c294 ("bpf: Constant map key + * tracking for prog array pokes") for details on verifier tracking. + * + * Note on clobber list: we need to stay in-line with BPF calling + * convention, so even if we don't end up using r0, r4, r5, we need + * to mark them as clobber so that LLVM doesn't end up using them + * before / after the call. + */ + asm volatile("r1 = %[ctx]\n\t" + "r2 = %[map]\n\t" + "r3 = %[slot]\n\t" + "call 12" + :: [ctx]"r"(ctx), [map]"r"(map), [slot]"i"(slot) + : "r0", "r1", "r2", "r3", "r4", "r5"); +} +#endif + +/* + * Helper structure used by eBPF C program + * to describe BPF map attributes to libbpf loader + */ +struct bpf_map_def { + unsigned int type; + unsigned int key_size; + unsigned int value_size; + unsigned int max_entries; + unsigned int map_flags; +}; + +enum libbpf_pin_type { + LIBBPF_PIN_NONE, + /* PIN_BY_NAME: pin maps by name (in /sys/fs/bpf by default) */ + LIBBPF_PIN_BY_NAME, +}; + +enum libbpf_tristate { + TRI_NO = 0, + TRI_YES = 1, + TRI_MODULE = 2, +}; + +#define __kconfig __attribute__((section(".kconfig"))) +#define __ksym __attribute__((section(".ksyms"))) + +#ifndef ___bpf_concat +#define ___bpf_concat(a, b) a ## b +#endif +#ifndef ___bpf_apply +#define ___bpf_apply(fn, n) ___bpf_concat(fn, n) +#endif +#ifndef ___bpf_nth +#define ___bpf_nth(_, _1, _2, _3, _4, _5, _6, _7, _8, _9, _a, _b, _c, N, ...) N +#endif +#ifndef ___bpf_narg +#define ___bpf_narg(...) \ + ___bpf_nth(_, ##__VA_ARGS__, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0) +#endif + +#define ___bpf_fill0(arr, p, x) do {} while (0) +#define ___bpf_fill1(arr, p, x) arr[p] = x +#define ___bpf_fill2(arr, p, x, args...) arr[p] = x; ___bpf_fill1(arr, p + 1, args) +#define ___bpf_fill3(arr, p, x, args...) arr[p] = x; ___bpf_fill2(arr, p + 1, args) +#define ___bpf_fill4(arr, p, x, args...) arr[p] = x; ___bpf_fill3(arr, p + 1, args) +#define ___bpf_fill5(arr, p, x, args...) arr[p] = x; ___bpf_fill4(arr, p + 1, args) +#define ___bpf_fill6(arr, p, x, args...) arr[p] = x; ___bpf_fill5(arr, p + 1, args) +#define ___bpf_fill7(arr, p, x, args...) arr[p] = x; ___bpf_fill6(arr, p + 1, args) +#define ___bpf_fill8(arr, p, x, args...) arr[p] = x; ___bpf_fill7(arr, p + 1, args) +#define ___bpf_fill9(arr, p, x, args...) arr[p] = x; ___bpf_fill8(arr, p + 1, args) +#define ___bpf_fill10(arr, p, x, args...) arr[p] = x; ___bpf_fill9(arr, p + 1, args) +#define ___bpf_fill11(arr, p, x, args...) arr[p] = x; ___bpf_fill10(arr, p + 1, args) +#define ___bpf_fill12(arr, p, x, args...) arr[p] = x; ___bpf_fill11(arr, p + 1, args) +#define ___bpf_fill(arr, args...) \ + ___bpf_apply(___bpf_fill, ___bpf_narg(args))(arr, 0, args) + +/* + * BPF_SEQ_PRINTF to wrap bpf_seq_printf to-be-printed values + * in a structure. + */ +#define BPF_SEQ_PRINTF(seq, fmt, args...) \ +({ \ + static const char ___fmt[] = fmt; \ + unsigned long long ___param[___bpf_narg(args)]; \ + \ + _Pragma("GCC diagnostic push") \ + _Pragma("GCC diagnostic ignored \"-Wint-conversion\"") \ + ___bpf_fill(___param, args); \ + _Pragma("GCC diagnostic pop") \ + \ + bpf_seq_printf(seq, ___fmt, sizeof(___fmt), \ + ___param, sizeof(___param)); \ +}) + +/* + * BPF_SNPRINTF wraps the bpf_snprintf helper with variadic arguments instead of + * an array of u64. + */ +#define BPF_SNPRINTF(out, out_size, fmt, args...) \ +({ \ + static const char ___fmt[] = fmt; \ + unsigned long long ___param[___bpf_narg(args)]; \ + \ + _Pragma("GCC diagnostic push") \ + _Pragma("GCC diagnostic ignored \"-Wint-conversion\"") \ + ___bpf_fill(___param, args); \ + _Pragma("GCC diagnostic pop") \ + \ + bpf_snprintf(out, out_size, ___fmt, \ + ___param, sizeof(___param)); \ +}) + +#ifdef BPF_NO_GLOBAL_DATA +#define BPF_PRINTK_FMT_MOD +#else +#define BPF_PRINTK_FMT_MOD static const +#endif + +#define __bpf_printk(fmt, ...) \ +({ \ + BPF_PRINTK_FMT_MOD char ____fmt[] = fmt; \ + bpf_trace_printk(____fmt, sizeof(____fmt), \ + ##__VA_ARGS__); \ +}) + +/* + * __bpf_vprintk wraps the bpf_trace_vprintk helper with variadic arguments + * instead of an array of u64. + */ +#define __bpf_vprintk(fmt, args...) \ +({ \ + static const char ___fmt[] = fmt; \ + unsigned long long ___param[___bpf_narg(args)]; \ + \ + _Pragma("GCC diagnostic push") \ + _Pragma("GCC diagnostic ignored \"-Wint-conversion\"") \ + ___bpf_fill(___param, args); \ + _Pragma("GCC diagnostic pop") \ + \ + bpf_trace_vprintk(___fmt, sizeof(___fmt), \ + ___param, sizeof(___param)); \ +}) + +/* Use __bpf_printk when bpf_printk call has 3 or fewer fmt args + * Otherwise use __bpf_vprintk + */ +#define ___bpf_pick_printk(...) \ + ___bpf_nth(_, ##__VA_ARGS__, __bpf_vprintk, __bpf_vprintk, __bpf_vprintk, \ + __bpf_vprintk, __bpf_vprintk, __bpf_vprintk, __bpf_vprintk, \ + __bpf_vprintk, __bpf_vprintk, __bpf_printk /*3*/, __bpf_printk /*2*/,\ + __bpf_printk /*1*/, __bpf_printk /*0*/) + +/* Helper macro to print out debug messages */ +#define bpf_printk(fmt, args...) ___bpf_pick_printk(args)(fmt, ##args) + +#endif diff --git a/internal/ebpf/spike/c/bpf_tracing.h b/internal/ebpf/spike/c/bpf_tracing.h new file mode 100644 index 000000000..db05a5937 --- /dev/null +++ b/internal/ebpf/spike/c/bpf_tracing.h @@ -0,0 +1,492 @@ +/* SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause) */ +#ifndef __BPF_TRACING_H__ +#define __BPF_TRACING_H__ + +/* Scan the ARCH passed in from ARCH env variable (see Makefile) */ +#if defined(__TARGET_ARCH_x86) + #define bpf_target_x86 + #define bpf_target_defined +#elif defined(__TARGET_ARCH_s390) + #define bpf_target_s390 + #define bpf_target_defined +#elif defined(__TARGET_ARCH_arm) + #define bpf_target_arm + #define bpf_target_defined +#elif defined(__TARGET_ARCH_arm64) + #define bpf_target_arm64 + #define bpf_target_defined +#elif defined(__TARGET_ARCH_mips) + #define bpf_target_mips + #define bpf_target_defined +#elif defined(__TARGET_ARCH_powerpc) + #define bpf_target_powerpc + #define bpf_target_defined +#elif defined(__TARGET_ARCH_sparc) + #define bpf_target_sparc + #define bpf_target_defined +#elif defined(__TARGET_ARCH_riscv) + #define bpf_target_riscv + #define bpf_target_defined +#else + +/* Fall back to what the compiler says */ +#if defined(__x86_64__) + #define bpf_target_x86 + #define bpf_target_defined +#elif defined(__s390__) + #define bpf_target_s390 + #define bpf_target_defined +#elif defined(__arm__) + #define bpf_target_arm + #define bpf_target_defined +#elif defined(__aarch64__) + #define bpf_target_arm64 + #define bpf_target_defined +#elif defined(__mips__) + #define bpf_target_mips + #define bpf_target_defined +#elif defined(__powerpc__) + #define bpf_target_powerpc + #define bpf_target_defined +#elif defined(__sparc__) + #define bpf_target_sparc + #define bpf_target_defined +#elif defined(__riscv) && __riscv_xlen == 64 + #define bpf_target_riscv + #define bpf_target_defined +#endif /* no compiler target */ + +#endif + +#ifndef __BPF_TARGET_MISSING +#define __BPF_TARGET_MISSING "GCC error \"Must specify a BPF target arch via __TARGET_ARCH_xxx\"" +#endif + +#if defined(bpf_target_x86) + +#if defined(__KERNEL__) || defined(__VMLINUX_H__) + +#define PT_REGS_PARM1(x) ((x)->di) +#define PT_REGS_PARM2(x) ((x)->si) +#define PT_REGS_PARM3(x) ((x)->dx) +#define PT_REGS_PARM4(x) ((x)->cx) +#define PT_REGS_PARM5(x) ((x)->r8) +#define PT_REGS_RET(x) ((x)->sp) +#define PT_REGS_FP(x) ((x)->bp) +#define PT_REGS_RC(x) ((x)->ax) +#define PT_REGS_SP(x) ((x)->sp) +#define PT_REGS_IP(x) ((x)->ip) + +#define PT_REGS_PARM1_CORE(x) BPF_CORE_READ((x), di) +#define PT_REGS_PARM2_CORE(x) BPF_CORE_READ((x), si) +#define PT_REGS_PARM3_CORE(x) BPF_CORE_READ((x), dx) +#define PT_REGS_PARM4_CORE(x) BPF_CORE_READ((x), cx) +#define PT_REGS_PARM5_CORE(x) BPF_CORE_READ((x), r8) +#define PT_REGS_RET_CORE(x) BPF_CORE_READ((x), sp) +#define PT_REGS_FP_CORE(x) BPF_CORE_READ((x), bp) +#define PT_REGS_RC_CORE(x) BPF_CORE_READ((x), ax) +#define PT_REGS_SP_CORE(x) BPF_CORE_READ((x), sp) +#define PT_REGS_IP_CORE(x) BPF_CORE_READ((x), ip) + +#else + +#ifdef __i386__ +/* i386 kernel is built with -mregparm=3 */ +#define PT_REGS_PARM1(x) ((x)->eax) +#define PT_REGS_PARM2(x) ((x)->edx) +#define PT_REGS_PARM3(x) ((x)->ecx) +#define PT_REGS_PARM4(x) 0 +#define PT_REGS_PARM5(x) 0 +#define PT_REGS_RET(x) ((x)->esp) +#define PT_REGS_FP(x) ((x)->ebp) +#define PT_REGS_RC(x) ((x)->eax) +#define PT_REGS_SP(x) ((x)->esp) +#define PT_REGS_IP(x) ((x)->eip) + +#define PT_REGS_PARM1_CORE(x) BPF_CORE_READ((x), eax) +#define PT_REGS_PARM2_CORE(x) BPF_CORE_READ((x), edx) +#define PT_REGS_PARM3_CORE(x) BPF_CORE_READ((x), ecx) +#define PT_REGS_PARM4_CORE(x) 0 +#define PT_REGS_PARM5_CORE(x) 0 +#define PT_REGS_RET_CORE(x) BPF_CORE_READ((x), esp) +#define PT_REGS_FP_CORE(x) BPF_CORE_READ((x), ebp) +#define PT_REGS_RC_CORE(x) BPF_CORE_READ((x), eax) +#define PT_REGS_SP_CORE(x) BPF_CORE_READ((x), esp) +#define PT_REGS_IP_CORE(x) BPF_CORE_READ((x), eip) + +#else + +#define PT_REGS_PARM1(x) ((x)->rdi) +#define PT_REGS_PARM2(x) ((x)->rsi) +#define PT_REGS_PARM3(x) ((x)->rdx) +#define PT_REGS_PARM4(x) ((x)->rcx) +#define PT_REGS_PARM5(x) ((x)->r8) +#define PT_REGS_RET(x) ((x)->rsp) +#define PT_REGS_FP(x) ((x)->rbp) +#define PT_REGS_RC(x) ((x)->rax) +#define PT_REGS_SP(x) ((x)->rsp) +#define PT_REGS_IP(x) ((x)->rip) + +#define PT_REGS_PARM1_CORE(x) BPF_CORE_READ((x), rdi) +#define PT_REGS_PARM2_CORE(x) BPF_CORE_READ((x), rsi) +#define PT_REGS_PARM3_CORE(x) BPF_CORE_READ((x), rdx) +#define PT_REGS_PARM4_CORE(x) BPF_CORE_READ((x), rcx) +#define PT_REGS_PARM5_CORE(x) BPF_CORE_READ((x), r8) +#define PT_REGS_RET_CORE(x) BPF_CORE_READ((x), rsp) +#define PT_REGS_FP_CORE(x) BPF_CORE_READ((x), rbp) +#define PT_REGS_RC_CORE(x) BPF_CORE_READ((x), rax) +#define PT_REGS_SP_CORE(x) BPF_CORE_READ((x), rsp) +#define PT_REGS_IP_CORE(x) BPF_CORE_READ((x), rip) + +#endif +#endif + +#elif defined(bpf_target_s390) + +/* s390 provides user_pt_regs instead of struct pt_regs to userspace */ +struct pt_regs; +#define PT_REGS_S390 const volatile user_pt_regs +#define PT_REGS_PARM1(x) (((PT_REGS_S390 *)(x))->gprs[2]) +#define PT_REGS_PARM2(x) (((PT_REGS_S390 *)(x))->gprs[3]) +#define PT_REGS_PARM3(x) (((PT_REGS_S390 *)(x))->gprs[4]) +#define PT_REGS_PARM4(x) (((PT_REGS_S390 *)(x))->gprs[5]) +#define PT_REGS_PARM5(x) (((PT_REGS_S390 *)(x))->gprs[6]) +#define PT_REGS_RET(x) (((PT_REGS_S390 *)(x))->gprs[14]) +/* Works only with CONFIG_FRAME_POINTER */ +#define PT_REGS_FP(x) (((PT_REGS_S390 *)(x))->gprs[11]) +#define PT_REGS_RC(x) (((PT_REGS_S390 *)(x))->gprs[2]) +#define PT_REGS_SP(x) (((PT_REGS_S390 *)(x))->gprs[15]) +#define PT_REGS_IP(x) (((PT_REGS_S390 *)(x))->psw.addr) + +#define PT_REGS_PARM1_CORE(x) BPF_CORE_READ((PT_REGS_S390 *)(x), gprs[2]) +#define PT_REGS_PARM2_CORE(x) BPF_CORE_READ((PT_REGS_S390 *)(x), gprs[3]) +#define PT_REGS_PARM3_CORE(x) BPF_CORE_READ((PT_REGS_S390 *)(x), gprs[4]) +#define PT_REGS_PARM4_CORE(x) BPF_CORE_READ((PT_REGS_S390 *)(x), gprs[5]) +#define PT_REGS_PARM5_CORE(x) BPF_CORE_READ((PT_REGS_S390 *)(x), gprs[6]) +#define PT_REGS_RET_CORE(x) BPF_CORE_READ((PT_REGS_S390 *)(x), gprs[14]) +#define PT_REGS_FP_CORE(x) BPF_CORE_READ((PT_REGS_S390 *)(x), gprs[11]) +#define PT_REGS_RC_CORE(x) BPF_CORE_READ((PT_REGS_S390 *)(x), gprs[2]) +#define PT_REGS_SP_CORE(x) BPF_CORE_READ((PT_REGS_S390 *)(x), gprs[15]) +#define PT_REGS_IP_CORE(x) BPF_CORE_READ((PT_REGS_S390 *)(x), psw.addr) + +#elif defined(bpf_target_arm) + +#define PT_REGS_PARM1(x) ((x)->uregs[0]) +#define PT_REGS_PARM2(x) ((x)->uregs[1]) +#define PT_REGS_PARM3(x) ((x)->uregs[2]) +#define PT_REGS_PARM4(x) ((x)->uregs[3]) +#define PT_REGS_PARM5(x) ((x)->uregs[4]) +#define PT_REGS_RET(x) ((x)->uregs[14]) +#define PT_REGS_FP(x) ((x)->uregs[11]) /* Works only with CONFIG_FRAME_POINTER */ +#define PT_REGS_RC(x) ((x)->uregs[0]) +#define PT_REGS_SP(x) ((x)->uregs[13]) +#define PT_REGS_IP(x) ((x)->uregs[12]) + +#define PT_REGS_PARM1_CORE(x) BPF_CORE_READ((x), uregs[0]) +#define PT_REGS_PARM2_CORE(x) BPF_CORE_READ((x), uregs[1]) +#define PT_REGS_PARM3_CORE(x) BPF_CORE_READ((x), uregs[2]) +#define PT_REGS_PARM4_CORE(x) BPF_CORE_READ((x), uregs[3]) +#define PT_REGS_PARM5_CORE(x) BPF_CORE_READ((x), uregs[4]) +#define PT_REGS_RET_CORE(x) BPF_CORE_READ((x), uregs[14]) +#define PT_REGS_FP_CORE(x) BPF_CORE_READ((x), uregs[11]) +#define PT_REGS_RC_CORE(x) BPF_CORE_READ((x), uregs[0]) +#define PT_REGS_SP_CORE(x) BPF_CORE_READ((x), uregs[13]) +#define PT_REGS_IP_CORE(x) BPF_CORE_READ((x), uregs[12]) + +#elif defined(bpf_target_arm64) + +/* arm64 provides struct user_pt_regs instead of struct pt_regs to userspace */ +struct pt_regs; +#define PT_REGS_ARM64 const volatile struct user_pt_regs +#define PT_REGS_PARM1(x) (((PT_REGS_ARM64 *)(x))->regs[0]) +#define PT_REGS_PARM2(x) (((PT_REGS_ARM64 *)(x))->regs[1]) +#define PT_REGS_PARM3(x) (((PT_REGS_ARM64 *)(x))->regs[2]) +#define PT_REGS_PARM4(x) (((PT_REGS_ARM64 *)(x))->regs[3]) +#define PT_REGS_PARM5(x) (((PT_REGS_ARM64 *)(x))->regs[4]) +#define PT_REGS_RET(x) (((PT_REGS_ARM64 *)(x))->regs[30]) +/* Works only with CONFIG_FRAME_POINTER */ +#define PT_REGS_FP(x) (((PT_REGS_ARM64 *)(x))->regs[29]) +#define PT_REGS_RC(x) (((PT_REGS_ARM64 *)(x))->regs[0]) +#define PT_REGS_SP(x) (((PT_REGS_ARM64 *)(x))->sp) +#define PT_REGS_IP(x) (((PT_REGS_ARM64 *)(x))->pc) + +#define PT_REGS_PARM1_CORE(x) BPF_CORE_READ((PT_REGS_ARM64 *)(x), regs[0]) +#define PT_REGS_PARM2_CORE(x) BPF_CORE_READ((PT_REGS_ARM64 *)(x), regs[1]) +#define PT_REGS_PARM3_CORE(x) BPF_CORE_READ((PT_REGS_ARM64 *)(x), regs[2]) +#define PT_REGS_PARM4_CORE(x) BPF_CORE_READ((PT_REGS_ARM64 *)(x), regs[3]) +#define PT_REGS_PARM5_CORE(x) BPF_CORE_READ((PT_REGS_ARM64 *)(x), regs[4]) +#define PT_REGS_RET_CORE(x) BPF_CORE_READ((PT_REGS_ARM64 *)(x), regs[30]) +#define PT_REGS_FP_CORE(x) BPF_CORE_READ((PT_REGS_ARM64 *)(x), regs[29]) +#define PT_REGS_RC_CORE(x) BPF_CORE_READ((PT_REGS_ARM64 *)(x), regs[0]) +#define PT_REGS_SP_CORE(x) BPF_CORE_READ((PT_REGS_ARM64 *)(x), sp) +#define PT_REGS_IP_CORE(x) BPF_CORE_READ((PT_REGS_ARM64 *)(x), pc) + +#elif defined(bpf_target_mips) + +#define PT_REGS_PARM1(x) ((x)->regs[4]) +#define PT_REGS_PARM2(x) ((x)->regs[5]) +#define PT_REGS_PARM3(x) ((x)->regs[6]) +#define PT_REGS_PARM4(x) ((x)->regs[7]) +#define PT_REGS_PARM5(x) ((x)->regs[8]) +#define PT_REGS_RET(x) ((x)->regs[31]) +#define PT_REGS_FP(x) ((x)->regs[30]) /* Works only with CONFIG_FRAME_POINTER */ +#define PT_REGS_RC(x) ((x)->regs[2]) +#define PT_REGS_SP(x) ((x)->regs[29]) +#define PT_REGS_IP(x) ((x)->cp0_epc) + +#define PT_REGS_PARM1_CORE(x) BPF_CORE_READ((x), regs[4]) +#define PT_REGS_PARM2_CORE(x) BPF_CORE_READ((x), regs[5]) +#define PT_REGS_PARM3_CORE(x) BPF_CORE_READ((x), regs[6]) +#define PT_REGS_PARM4_CORE(x) BPF_CORE_READ((x), regs[7]) +#define PT_REGS_PARM5_CORE(x) BPF_CORE_READ((x), regs[8]) +#define PT_REGS_RET_CORE(x) BPF_CORE_READ((x), regs[31]) +#define PT_REGS_FP_CORE(x) BPF_CORE_READ((x), regs[30]) +#define PT_REGS_RC_CORE(x) BPF_CORE_READ((x), regs[2]) +#define PT_REGS_SP_CORE(x) BPF_CORE_READ((x), regs[29]) +#define PT_REGS_IP_CORE(x) BPF_CORE_READ((x), cp0_epc) + +#elif defined(bpf_target_powerpc) + +#define PT_REGS_PARM1(x) ((x)->gpr[3]) +#define PT_REGS_PARM2(x) ((x)->gpr[4]) +#define PT_REGS_PARM3(x) ((x)->gpr[5]) +#define PT_REGS_PARM4(x) ((x)->gpr[6]) +#define PT_REGS_PARM5(x) ((x)->gpr[7]) +#define PT_REGS_RC(x) ((x)->gpr[3]) +#define PT_REGS_SP(x) ((x)->sp) +#define PT_REGS_IP(x) ((x)->nip) + +#define PT_REGS_PARM1_CORE(x) BPF_CORE_READ((x), gpr[3]) +#define PT_REGS_PARM2_CORE(x) BPF_CORE_READ((x), gpr[4]) +#define PT_REGS_PARM3_CORE(x) BPF_CORE_READ((x), gpr[5]) +#define PT_REGS_PARM4_CORE(x) BPF_CORE_READ((x), gpr[6]) +#define PT_REGS_PARM5_CORE(x) BPF_CORE_READ((x), gpr[7]) +#define PT_REGS_RC_CORE(x) BPF_CORE_READ((x), gpr[3]) +#define PT_REGS_SP_CORE(x) BPF_CORE_READ((x), sp) +#define PT_REGS_IP_CORE(x) BPF_CORE_READ((x), nip) + +#elif defined(bpf_target_sparc) + +#define PT_REGS_PARM1(x) ((x)->u_regs[UREG_I0]) +#define PT_REGS_PARM2(x) ((x)->u_regs[UREG_I1]) +#define PT_REGS_PARM3(x) ((x)->u_regs[UREG_I2]) +#define PT_REGS_PARM4(x) ((x)->u_regs[UREG_I3]) +#define PT_REGS_PARM5(x) ((x)->u_regs[UREG_I4]) +#define PT_REGS_RET(x) ((x)->u_regs[UREG_I7]) +#define PT_REGS_RC(x) ((x)->u_regs[UREG_I0]) +#define PT_REGS_SP(x) ((x)->u_regs[UREG_FP]) + +#define PT_REGS_PARM1_CORE(x) BPF_CORE_READ((x), u_regs[UREG_I0]) +#define PT_REGS_PARM2_CORE(x) BPF_CORE_READ((x), u_regs[UREG_I1]) +#define PT_REGS_PARM3_CORE(x) BPF_CORE_READ((x), u_regs[UREG_I2]) +#define PT_REGS_PARM4_CORE(x) BPF_CORE_READ((x), u_regs[UREG_I3]) +#define PT_REGS_PARM5_CORE(x) BPF_CORE_READ((x), u_regs[UREG_I4]) +#define PT_REGS_RET_CORE(x) BPF_CORE_READ((x), u_regs[UREG_I7]) +#define PT_REGS_RC_CORE(x) BPF_CORE_READ((x), u_regs[UREG_I0]) +#define PT_REGS_SP_CORE(x) BPF_CORE_READ((x), u_regs[UREG_FP]) + +/* Should this also be a bpf_target check for the sparc case? */ +#if defined(__arch64__) +#define PT_REGS_IP(x) ((x)->tpc) +#define PT_REGS_IP_CORE(x) BPF_CORE_READ((x), tpc) +#else +#define PT_REGS_IP(x) ((x)->pc) +#define PT_REGS_IP_CORE(x) BPF_CORE_READ((x), pc) +#endif + +#elif defined(bpf_target_riscv) + +struct pt_regs; +#define PT_REGS_RV const volatile struct user_regs_struct +#define PT_REGS_PARM1(x) (((PT_REGS_RV *)(x))->a0) +#define PT_REGS_PARM2(x) (((PT_REGS_RV *)(x))->a1) +#define PT_REGS_PARM3(x) (((PT_REGS_RV *)(x))->a2) +#define PT_REGS_PARM4(x) (((PT_REGS_RV *)(x))->a3) +#define PT_REGS_PARM5(x) (((PT_REGS_RV *)(x))->a4) +#define PT_REGS_RET(x) (((PT_REGS_RV *)(x))->ra) +#define PT_REGS_FP(x) (((PT_REGS_RV *)(x))->s5) +#define PT_REGS_RC(x) (((PT_REGS_RV *)(x))->a5) +#define PT_REGS_SP(x) (((PT_REGS_RV *)(x))->sp) +#define PT_REGS_IP(x) (((PT_REGS_RV *)(x))->epc) + +#define PT_REGS_PARM1_CORE(x) BPF_CORE_READ((PT_REGS_RV *)(x), a0) +#define PT_REGS_PARM2_CORE(x) BPF_CORE_READ((PT_REGS_RV *)(x), a1) +#define PT_REGS_PARM3_CORE(x) BPF_CORE_READ((PT_REGS_RV *)(x), a2) +#define PT_REGS_PARM4_CORE(x) BPF_CORE_READ((PT_REGS_RV *)(x), a3) +#define PT_REGS_PARM5_CORE(x) BPF_CORE_READ((PT_REGS_RV *)(x), a4) +#define PT_REGS_RET_CORE(x) BPF_CORE_READ((PT_REGS_RV *)(x), ra) +#define PT_REGS_FP_CORE(x) BPF_CORE_READ((PT_REGS_RV *)(x), fp) +#define PT_REGS_RC_CORE(x) BPF_CORE_READ((PT_REGS_RV *)(x), a5) +#define PT_REGS_SP_CORE(x) BPF_CORE_READ((PT_REGS_RV *)(x), sp) +#define PT_REGS_IP_CORE(x) BPF_CORE_READ((PT_REGS_RV *)(x), epc) + +#endif + +#if defined(bpf_target_powerpc) +#define BPF_KPROBE_READ_RET_IP(ip, ctx) ({ (ip) = (ctx)->link; }) +#define BPF_KRETPROBE_READ_RET_IP BPF_KPROBE_READ_RET_IP +#elif defined(bpf_target_sparc) +#define BPF_KPROBE_READ_RET_IP(ip, ctx) ({ (ip) = PT_REGS_RET(ctx); }) +#define BPF_KRETPROBE_READ_RET_IP BPF_KPROBE_READ_RET_IP +#elif defined(bpf_target_defined) +#define BPF_KPROBE_READ_RET_IP(ip, ctx) \ + ({ bpf_probe_read_kernel(&(ip), sizeof(ip), (void *)PT_REGS_RET(ctx)); }) +#define BPF_KRETPROBE_READ_RET_IP(ip, ctx) \ + ({ bpf_probe_read_kernel(&(ip), sizeof(ip), \ + (void *)(PT_REGS_FP(ctx) + sizeof(ip))); }) +#endif + +#if !defined(bpf_target_defined) + +#define PT_REGS_PARM1(x) ({ _Pragma(__BPF_TARGET_MISSING); 0l; }) +#define PT_REGS_PARM2(x) ({ _Pragma(__BPF_TARGET_MISSING); 0l; }) +#define PT_REGS_PARM3(x) ({ _Pragma(__BPF_TARGET_MISSING); 0l; }) +#define PT_REGS_PARM4(x) ({ _Pragma(__BPF_TARGET_MISSING); 0l; }) +#define PT_REGS_PARM5(x) ({ _Pragma(__BPF_TARGET_MISSING); 0l; }) +#define PT_REGS_RET(x) ({ _Pragma(__BPF_TARGET_MISSING); 0l; }) +#define PT_REGS_FP(x) ({ _Pragma(__BPF_TARGET_MISSING); 0l; }) +#define PT_REGS_RC(x) ({ _Pragma(__BPF_TARGET_MISSING); 0l; }) +#define PT_REGS_SP(x) ({ _Pragma(__BPF_TARGET_MISSING); 0l; }) +#define PT_REGS_IP(x) ({ _Pragma(__BPF_TARGET_MISSING); 0l; }) + +#define PT_REGS_PARM1_CORE(x) ({ _Pragma(__BPF_TARGET_MISSING); 0l; }) +#define PT_REGS_PARM2_CORE(x) ({ _Pragma(__BPF_TARGET_MISSING); 0l; }) +#define PT_REGS_PARM3_CORE(x) ({ _Pragma(__BPF_TARGET_MISSING); 0l; }) +#define PT_REGS_PARM4_CORE(x) ({ _Pragma(__BPF_TARGET_MISSING); 0l; }) +#define PT_REGS_PARM5_CORE(x) ({ _Pragma(__BPF_TARGET_MISSING); 0l; }) +#define PT_REGS_RET_CORE(x) ({ _Pragma(__BPF_TARGET_MISSING); 0l; }) +#define PT_REGS_FP_CORE(x) ({ _Pragma(__BPF_TARGET_MISSING); 0l; }) +#define PT_REGS_RC_CORE(x) ({ _Pragma(__BPF_TARGET_MISSING); 0l; }) +#define PT_REGS_SP_CORE(x) ({ _Pragma(__BPF_TARGET_MISSING); 0l; }) +#define PT_REGS_IP_CORE(x) ({ _Pragma(__BPF_TARGET_MISSING); 0l; }) + +#define BPF_KPROBE_READ_RET_IP(ip, ctx) ({ _Pragma(__BPF_TARGET_MISSING); 0l; }) +#define BPF_KRETPROBE_READ_RET_IP(ip, ctx) ({ _Pragma(__BPF_TARGET_MISSING); 0l; }) + +#endif /* !defined(bpf_target_defined) */ + +#ifndef ___bpf_concat +#define ___bpf_concat(a, b) a ## b +#endif +#ifndef ___bpf_apply +#define ___bpf_apply(fn, n) ___bpf_concat(fn, n) +#endif +#ifndef ___bpf_nth +#define ___bpf_nth(_, _1, _2, _3, _4, _5, _6, _7, _8, _9, _a, _b, _c, N, ...) N +#endif +#ifndef ___bpf_narg +#define ___bpf_narg(...) \ + ___bpf_nth(_, ##__VA_ARGS__, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0) +#endif + +#define ___bpf_ctx_cast0() ctx +#define ___bpf_ctx_cast1(x) ___bpf_ctx_cast0(), (void *)ctx[0] +#define ___bpf_ctx_cast2(x, args...) ___bpf_ctx_cast1(args), (void *)ctx[1] +#define ___bpf_ctx_cast3(x, args...) ___bpf_ctx_cast2(args), (void *)ctx[2] +#define ___bpf_ctx_cast4(x, args...) ___bpf_ctx_cast3(args), (void *)ctx[3] +#define ___bpf_ctx_cast5(x, args...) ___bpf_ctx_cast4(args), (void *)ctx[4] +#define ___bpf_ctx_cast6(x, args...) ___bpf_ctx_cast5(args), (void *)ctx[5] +#define ___bpf_ctx_cast7(x, args...) ___bpf_ctx_cast6(args), (void *)ctx[6] +#define ___bpf_ctx_cast8(x, args...) ___bpf_ctx_cast7(args), (void *)ctx[7] +#define ___bpf_ctx_cast9(x, args...) ___bpf_ctx_cast8(args), (void *)ctx[8] +#define ___bpf_ctx_cast10(x, args...) ___bpf_ctx_cast9(args), (void *)ctx[9] +#define ___bpf_ctx_cast11(x, args...) ___bpf_ctx_cast10(args), (void *)ctx[10] +#define ___bpf_ctx_cast12(x, args...) ___bpf_ctx_cast11(args), (void *)ctx[11] +#define ___bpf_ctx_cast(args...) \ + ___bpf_apply(___bpf_ctx_cast, ___bpf_narg(args))(args) + +/* + * BPF_PROG is a convenience wrapper for generic tp_btf/fentry/fexit and + * similar kinds of BPF programs, that accept input arguments as a single + * pointer to untyped u64 array, where each u64 can actually be a typed + * pointer or integer of different size. Instead of requring user to write + * manual casts and work with array elements by index, BPF_PROG macro + * allows user to declare a list of named and typed input arguments in the + * same syntax as for normal C function. All the casting is hidden and + * performed transparently, while user code can just assume working with + * function arguments of specified type and name. + * + * Original raw context argument is preserved as well as 'ctx' argument. + * This is useful when using BPF helpers that expect original context + * as one of the parameters (e.g., for bpf_perf_event_output()). + */ +#define BPF_PROG(name, args...) \ +name(unsigned long long *ctx); \ +static __attribute__((always_inline)) typeof(name(0)) \ +____##name(unsigned long long *ctx, ##args); \ +typeof(name(0)) name(unsigned long long *ctx) \ +{ \ + _Pragma("GCC diagnostic push") \ + _Pragma("GCC diagnostic ignored \"-Wint-conversion\"") \ + return ____##name(___bpf_ctx_cast(args)); \ + _Pragma("GCC diagnostic pop") \ +} \ +static __attribute__((always_inline)) typeof(name(0)) \ +____##name(unsigned long long *ctx, ##args) + +struct pt_regs; + +#define ___bpf_kprobe_args0() ctx +#define ___bpf_kprobe_args1(x) \ + ___bpf_kprobe_args0(), (void *)PT_REGS_PARM1(ctx) +#define ___bpf_kprobe_args2(x, args...) \ + ___bpf_kprobe_args1(args), (void *)PT_REGS_PARM2(ctx) +#define ___bpf_kprobe_args3(x, args...) \ + ___bpf_kprobe_args2(args), (void *)PT_REGS_PARM3(ctx) +#define ___bpf_kprobe_args4(x, args...) \ + ___bpf_kprobe_args3(args), (void *)PT_REGS_PARM4(ctx) +#define ___bpf_kprobe_args5(x, args...) \ + ___bpf_kprobe_args4(args), (void *)PT_REGS_PARM5(ctx) +#define ___bpf_kprobe_args(args...) \ + ___bpf_apply(___bpf_kprobe_args, ___bpf_narg(args))(args) + +/* + * BPF_KPROBE serves the same purpose for kprobes as BPF_PROG for + * tp_btf/fentry/fexit BPF programs. It hides the underlying platform-specific + * low-level way of getting kprobe input arguments from struct pt_regs, and + * provides a familiar typed and named function arguments syntax and + * semantics of accessing kprobe input paremeters. + * + * Original struct pt_regs* context is preserved as 'ctx' argument. This might + * be necessary when using BPF helpers like bpf_perf_event_output(). + */ +#define BPF_KPROBE(name, args...) \ +name(struct pt_regs *ctx); \ +static __attribute__((always_inline)) typeof(name(0)) \ +____##name(struct pt_regs *ctx, ##args); \ +typeof(name(0)) name(struct pt_regs *ctx) \ +{ \ + _Pragma("GCC diagnostic push") \ + _Pragma("GCC diagnostic ignored \"-Wint-conversion\"") \ + return ____##name(___bpf_kprobe_args(args)); \ + _Pragma("GCC diagnostic pop") \ +} \ +static __attribute__((always_inline)) typeof(name(0)) \ +____##name(struct pt_regs *ctx, ##args) + +#define ___bpf_kretprobe_args0() ctx +#define ___bpf_kretprobe_args1(x) \ + ___bpf_kretprobe_args0(), (void *)PT_REGS_RC(ctx) +#define ___bpf_kretprobe_args(args...) \ + ___bpf_apply(___bpf_kretprobe_args, ___bpf_narg(args))(args) + +/* + * BPF_KRETPROBE is similar to BPF_KPROBE, except, it only provides optional + * return value (in addition to `struct pt_regs *ctx`), but no input + * arguments, because they will be clobbered by the time probed function + * returns. + */ +#define BPF_KRETPROBE(name, args...) \ +name(struct pt_regs *ctx); \ +static __attribute__((always_inline)) typeof(name(0)) \ +____##name(struct pt_regs *ctx, ##args); \ +typeof(name(0)) name(struct pt_regs *ctx) \ +{ \ + _Pragma("GCC diagnostic push") \ + _Pragma("GCC diagnostic ignored \"-Wint-conversion\"") \ + return ____##name(___bpf_kretprobe_args(args)); \ + _Pragma("GCC diagnostic pop") \ +} \ +static __always_inline typeof(name(0)) ____##name(struct pt_regs *ctx, ##args) + +#endif diff --git a/internal/ebpf/spike/c/events.h b/internal/ebpf/spike/c/events.h new file mode 100644 index 000000000..49f3c5166 --- /dev/null +++ b/internal/ebpf/spike/c/events.h @@ -0,0 +1,49 @@ +/* Shared event and map definitions for the Linux eBPF spike. */ + +#pragma once + +#include "vmlinux.h" +#include "bpf_helpers.h" + +#define SPIKE_FILENAME_LEN 256 + +enum spike_event_kind { + SPIKE_EVENT_EXEC = 1, + SPIKE_EVENT_SNAPSHOT = 2, +}; + +struct spike_event { + u32 kind; + u32 pid; + u32 tgid; + u32 ppid; + u32 uid; + u32 gid; + u64 start_boottime; + u64 timestamp_ns; + u8 comm[TASK_COMM_LEN]; + u8 filename[SPIKE_FILENAME_LEN]; +}; + +struct { + __uint(type, BPF_MAP_TYPE_RINGBUF); + __uint(max_entries, 1 << 24); +} events SEC(".maps"); + +struct { + __uint(type, BPF_MAP_TYPE_ARRAY); + __uint(max_entries, 1); + __type(key, u32); + __type(value, u64); +} drop_count SEC(".maps"); + +static __always_inline void spike_account_drop(void) +{ + u32 key = 0; + u64 *count; + + count = bpf_map_lookup_elem(&drop_count, &key); + if (!count) + return; + __sync_fetch_and_add(count, 1); +} diff --git a/internal/ebpf/spike/c/execve.bpf.c b/internal/ebpf/spike/c/execve.bpf.c new file mode 100644 index 000000000..f04873228 --- /dev/null +++ b/internal/ebpf/spike/c/execve.bpf.c @@ -0,0 +1,53 @@ +//go:build ignore + +#include "events.h" +#include "bpf_core_read.h" +#include "bpf_tracing.h" + +char LICENSE[] SEC("license") = "Dual MIT/GPL"; + +SEC("tp/sched/sched_process_exec") +int handle_sched_process_exec(struct trace_event_raw_sched_process_exec *ctx) +{ + struct spike_event *e; + struct task_struct *task; + struct task_struct *parent; + const struct cred *cred; + u64 id; + u32 fname_off; + + e = bpf_ringbuf_reserve(&events, sizeof(*e), 0); + if (!e) { + spike_account_drop(); + return 0; + } + + __builtin_memset(e, 0, sizeof(*e)); + e->kind = SPIKE_EVENT_EXEC; + e->timestamp_ns = bpf_ktime_get_ns(); + + id = bpf_get_current_pid_tgid(); + e->tgid = id >> 32; + e->pid = (u32)id; + e->uid = bpf_get_current_uid_gid(); + e->gid = bpf_get_current_uid_gid() >> 32; + bpf_get_current_comm(&e->comm, sizeof(e->comm)); + + task = (struct task_struct *)bpf_get_current_task(); + e->start_boottime = BPF_CORE_READ(task, start_boottime); + parent = BPF_CORE_READ(task, real_parent); + if (parent) + e->ppid = BPF_CORE_READ(parent, tgid); + cred = BPF_CORE_READ(task, real_cred); + if (cred) { + e->uid = BPF_CORE_READ(cred, uid.val); + e->gid = BPF_CORE_READ(cred, gid.val); + } + + /* Filename is optional enrichment from the tracepoint payload. */ + fname_off = ctx->__data_loc_filename & 0xffff; + bpf_probe_read_kernel_str(&e->filename, sizeof(e->filename), (void *)ctx + fname_off); + + bpf_ringbuf_submit(e, 0); + return 0; +} diff --git a/internal/ebpf/spike/c/proc_iter.bpf.c b/internal/ebpf/spike/c/proc_iter.bpf.c new file mode 100644 index 000000000..daeafe163 --- /dev/null +++ b/internal/ebpf/spike/c/proc_iter.bpf.c @@ -0,0 +1,63 @@ +//go:build ignore + +#include "events.h" +#include "bpf_core_read.h" + +char LICENSE[] SEC("license") = "Dual MIT/GPL"; + +/* Task iterator baseline scanner. + * + * Intentionally omits bpf_d_path (available from Linux 5.10). Executable path + * and cmdline are left empty here and are filled best-effort from + * /proc//{exe,cmdline} in userspace. + * + * ctx->task is a trusted BTF pointer, so field access uses CO-RE direct reads + * rather than bpf_probe_read-based helpers. + */ +SEC("iter/task") +int dump_task(struct bpf_iter__task *ctx) +{ + struct task_struct *task; + struct task_struct *parent; + const struct cred *cred; + struct spike_event *e; + pid_t pid; + pid_t tgid; + + task = ctx->task; + if (!task) + return 0; + + /* Emit one record per thread-group leader. */ + pid = task->pid; + tgid = task->tgid; + if (pid != tgid) + return 0; + + e = bpf_ringbuf_reserve(&events, sizeof(*e), 0); + if (!e) { + spike_account_drop(); + return 0; + } + + __builtin_memset(e, 0, sizeof(*e)); + e->kind = SPIKE_EVENT_SNAPSHOT; + e->timestamp_ns = bpf_ktime_get_ns(); + e->pid = pid; + e->tgid = tgid; + e->start_boottime = task->start_boottime; + __builtin_memcpy(&e->comm, task->comm, sizeof(e->comm)); + + parent = task->real_parent; + if (parent) + e->ppid = parent->tgid; + + cred = task->real_cred; + if (cred) { + e->uid = cred->uid.val; + e->gid = cred->gid.val; + } + + bpf_ringbuf_submit(e, 0); + return 0; +} diff --git a/internal/ebpf/spike/c/vmlinux.h b/internal/ebpf/spike/c/vmlinux.h new file mode 100644 index 000000000..dc774a68b --- /dev/null +++ b/internal/ebpf/spike/c/vmlinux.h @@ -0,0 +1,149 @@ +/* Minimal CO-RE type skeletons for the Linux eBPF spike. + * Full kernel BTF is still required at load/attach time for iterators. + */ + +#pragma once + +typedef unsigned char __u8; +typedef short int __s16; +typedef short unsigned int __u16; +typedef int __s32; +typedef unsigned int __u32; +typedef long long int __s64; +typedef long long unsigned int __u64; + +typedef __u8 u8; +typedef __s16 s16; +typedef __u16 u16; +typedef __s32 s32; +typedef __u32 u32; +typedef __s64 s64; +typedef __u64 u64; + +typedef __u32 __wsum; +typedef __u16 __le16; +typedef __u16 __be16; +typedef __u32 __be32; +typedef __u64 __be64; + +typedef int pid_t; +typedef u32 uid_t; +typedef u32 gid_t; + +struct kuid_t { + uid_t val; +} __attribute__((preserve_access_index)); + +struct kgid_t { + gid_t val; +} __attribute__((preserve_access_index)); + +enum bpf_map_type { + BPF_MAP_TYPE_UNSPEC = 0, + BPF_MAP_TYPE_HASH = 1, + BPF_MAP_TYPE_ARRAY = 2, + BPF_MAP_TYPE_PROG_ARRAY = 3, + BPF_MAP_TYPE_PERF_EVENT_ARRAY = 4, + BPF_MAP_TYPE_PERCPU_HASH = 5, + BPF_MAP_TYPE_PERCPU_ARRAY = 6, + BPF_MAP_TYPE_STACK_TRACE = 7, + BPF_MAP_TYPE_CGROUP_ARRAY = 8, + BPF_MAP_TYPE_LRU_HASH = 9, + BPF_MAP_TYPE_LRU_PERCPU_HASH = 10, + BPF_MAP_TYPE_LPM_TRIE = 11, + BPF_MAP_TYPE_ARRAY_OF_MAPS = 12, + BPF_MAP_TYPE_HASH_OF_MAPS = 13, + BPF_MAP_TYPE_DEVMAP = 14, + BPF_MAP_TYPE_SOCKMAP = 15, + BPF_MAP_TYPE_CPUMAP = 16, + BPF_MAP_TYPE_XSKMAP = 17, + BPF_MAP_TYPE_SOCKHASH = 18, + BPF_MAP_TYPE_CGROUP_STORAGE = 19, + BPF_MAP_TYPE_REUSEPORT_SOCKARRAY = 20, + BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE = 21, + BPF_MAP_TYPE_QUEUE = 22, + BPF_MAP_TYPE_STACK = 23, + BPF_MAP_TYPE_SK_STORAGE = 24, + BPF_MAP_TYPE_DEVMAP_HASH = 25, + BPF_MAP_TYPE_STRUCT_OPS = 26, + BPF_MAP_TYPE_RINGBUF = 27, +}; + +#ifndef TASK_COMM_LEN +#define TASK_COMM_LEN 16 +#endif + +struct seq_file; + +struct bpf_iter_meta { + struct seq_file *seq; + u64 session_id; + u64 seq_num; +} __attribute__((preserve_access_index)); + +struct cred { + struct kuid_t uid; + struct kgid_t gid; + struct kuid_t euid; + struct kgid_t egid; +} __attribute__((preserve_access_index)); + +struct nsproxy { + struct mnt_namespace *mnt_ns; + struct uts_namespace *uts_ns; + struct ipc_namespace *ipc_ns; + struct pid_namespace *pid_ns_for_children; + struct net *net_ns; + struct cgroup_namespace *cgroup_ns; +} __attribute__((preserve_access_index)); + +struct mnt_namespace { + unsigned int ns_inum; +} __attribute__((preserve_access_index)); + +struct uts_namespace { + unsigned int ns_inum; +} __attribute__((preserve_access_index)); + +struct ipc_namespace { + unsigned int ns_inum; +} __attribute__((preserve_access_index)); + +struct pid_namespace { + unsigned int ns_inum; +} __attribute__((preserve_access_index)); + +struct net { + unsigned int ns_inum; +} __attribute__((preserve_access_index)); + +struct cgroup_namespace { + unsigned int ns_inum; +} __attribute__((preserve_access_index)); + +struct task_struct { + int pid; + int tgid; + struct task_struct *real_parent; + struct task_struct *group_leader; + const struct cred *real_cred; + struct nsproxy *nsproxy; + u64 start_boottime; + char comm[TASK_COMM_LEN]; +} __attribute__((preserve_access_index)); + +struct bpf_iter__task { + struct bpf_iter_meta *meta; + struct task_struct *task; +} __attribute__((preserve_access_index)); + +/* Layout for sched/sched_process_exec; filename follows via __data_loc. */ +struct trace_event_raw_sched_process_exec { + unsigned short common_type; + unsigned char common_flags; + unsigned char common_preempt_count; + int common_pid; + u32 __data_loc_filename; + pid_t pid; + pid_t old_pid; +}; diff --git a/internal/ebpf/spike/cmd/spike/main.go b/internal/ebpf/spike/cmd/spike/main.go new file mode 100644 index 000000000..27d16c474 --- /dev/null +++ b/internal/ebpf/spike/cmd/spike/main.go @@ -0,0 +1,47 @@ +//go:build linux + +/* + * Copyright 2026 Fibratus contributors + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package main + +import ( + "fmt" + "os" + "time" + + "github.com/rabbitstack/fibratus/internal/ebpf/spike" +) + +func main() { + duration := 2 * time.Second + if v := os.Getenv("SPIKE_DURATION"); v != "" { + if d, err := time.ParseDuration(v); err == nil { + duration = d + } + } + + result, err := spike.Run(duration) + if result != nil { + fmt.Print(spike.FormatReport(result)) + } + if err != nil { + fmt.Fprintf(os.Stderr, "spike failed: %v\n", err) + os.Exit(1) + } +} diff --git a/internal/ebpf/spike/enrich.go b/internal/ebpf/spike/enrich.go new file mode 100644 index 000000000..fa57410a3 --- /dev/null +++ b/internal/ebpf/spike/enrich.go @@ -0,0 +1,53 @@ +//go:build linux + +/* + * Copyright 2026 Fibratus contributors + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package spike + +import ( + "fmt" + "os" + "strings" +) + +// enrichFromProc best-effort reads /proc//{exe,cmdline}. Failures leave +// fields empty and never replace the iterator baseline scan. +func enrichFromProc(pid uint32) (exe string, cmdline string, err error) { + exeLink := fmt.Sprintf("/proc/%d/exe", pid) + exe, err = os.Readlink(exeLink) + if err != nil { + exe = "" + } + + raw, cerr := os.ReadFile(fmt.Sprintf("/proc/%d/cmdline", pid)) + if cerr != nil { + if err == nil { + err = cerr + } + return exe, "", err + } + parts := strings.Split(string(raw), "\x00") + var cleaned []string + for _, p := range parts { + if p != "" { + cleaned = append(cleaned, p) + } + } + return exe, strings.Join(cleaned, " "), err +} diff --git a/internal/ebpf/spike/event.go b/internal/ebpf/spike/event.go new file mode 100644 index 000000000..d4211d07d --- /dev/null +++ b/internal/ebpf/spike/event.go @@ -0,0 +1,35 @@ +//go:build linux + +/* + * Copyright 2026 Fibratus contributors + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package spike + +// spikeEvent mirrors struct spike_event in c/events.h. +type spikeEvent struct { + Kind uint32 + Pid uint32 + Tgid uint32 + Ppid uint32 + UID uint32 + GID uint32 + StartBoottime uint64 + TimestampNs uint64 + Comm [16]byte + Filename [256]byte +} diff --git a/internal/ebpf/spike/execve_bpfeb.go b/internal/ebpf/spike/execve_bpfeb.go new file mode 100644 index 000000000..50ee1ed7d --- /dev/null +++ b/internal/ebpf/spike/execve_bpfeb.go @@ -0,0 +1,136 @@ +// Code generated by bpf2go; DO NOT EDIT. +//go:build mips || mips64 || ppc64 || s390x + +package spike + +import ( + "bytes" + _ "embed" + "fmt" + "io" + + "github.com/cilium/ebpf" +) + +// loadExecve returns the embedded CollectionSpec for execve. +func loadExecve() (*ebpf.CollectionSpec, error) { + reader := bytes.NewReader(_ExecveBytes) + spec, err := ebpf.LoadCollectionSpecFromReader(reader) + if err != nil { + return nil, fmt.Errorf("can't load execve: %w", err) + } + + return spec, err +} + +// loadExecveObjects loads execve and converts it into a struct. +// +// The following types are suitable as obj argument: +// +// *execveObjects +// *execvePrograms +// *execveMaps +// +// See ebpf.CollectionSpec.LoadAndAssign documentation for details. +func loadExecveObjects(obj interface{}, opts *ebpf.CollectionOptions) error { + spec, err := loadExecve() + if err != nil { + return err + } + + return spec.LoadAndAssign(obj, opts) +} + +// execveSpecs contains maps and programs before they are loaded into the kernel. +// +// It can be passed ebpf.CollectionSpec.Assign. +type execveSpecs struct { + execveProgramSpecs + execveMapSpecs + execveVariableSpecs +} + +// execveProgramSpecs contains programs before they are loaded into the kernel. +// +// It can be passed ebpf.CollectionSpec.Assign. +type execveProgramSpecs struct { + HandleSchedProcessExec *ebpf.ProgramSpec `ebpf:"handle_sched_process_exec"` +} + +// execveMapSpecs contains maps before they are loaded into the kernel. +// +// It can be passed ebpf.CollectionSpec.Assign. +type execveMapSpecs struct { + DropCount *ebpf.MapSpec `ebpf:"drop_count"` + Events *ebpf.MapSpec `ebpf:"events"` +} + +// execveVariableSpecs contains global variables before they are loaded into the kernel. +// +// It can be passed ebpf.CollectionSpec.Assign. +type execveVariableSpecs struct { +} + +// execveObjects contains all objects after they have been loaded into the kernel. +// +// It can be passed to loadExecveObjects or ebpf.CollectionSpec.LoadAndAssign. +type execveObjects struct { + execvePrograms + execveMaps + execveVariables +} + +func (o *execveObjects) Close() error { + return _ExecveClose( + &o.execvePrograms, + &o.execveMaps, + ) +} + +// execveMaps contains all maps after they have been loaded into the kernel. +// +// It can be passed to loadExecveObjects or ebpf.CollectionSpec.LoadAndAssign. +type execveMaps struct { + DropCount *ebpf.Map `ebpf:"drop_count"` + Events *ebpf.Map `ebpf:"events"` +} + +func (m *execveMaps) Close() error { + return _ExecveClose( + m.DropCount, + m.Events, + ) +} + +// execveVariables contains all global variables after they have been loaded into the kernel. +// +// It can be passed to loadExecveObjects or ebpf.CollectionSpec.LoadAndAssign. +type execveVariables struct { +} + +// execvePrograms contains all programs after they have been loaded into the kernel. +// +// It can be passed to loadExecveObjects or ebpf.CollectionSpec.LoadAndAssign. +type execvePrograms struct { + HandleSchedProcessExec *ebpf.Program `ebpf:"handle_sched_process_exec"` +} + +func (p *execvePrograms) Close() error { + return _ExecveClose( + p.HandleSchedProcessExec, + ) +} + +func _ExecveClose(closers ...io.Closer) error { + for _, closer := range closers { + if err := closer.Close(); err != nil { + return err + } + } + return nil +} + +// Do not access this directly. +// +//go:embed execve_bpfeb.o +var _ExecveBytes []byte diff --git a/internal/ebpf/spike/execve_bpfeb.o b/internal/ebpf/spike/execve_bpfeb.o new file mode 100644 index 0000000000000000000000000000000000000000..2619d22368f11f0ea2697163b7ec3469982438fa GIT binary patch literal 6960 zcmb_gU2I%O6`uWb?KVG#w2di*-q2#!uCv*sB}56eHa{B@)f6iUkRqh(_3qeSynorf z>#mblEFwr%)dx#ZDWD?!P>CS%;0HwVWw&O)-JqO2x2xD{!N}@*H{?Tu zA-B)#9;Mjf>)BBAt&n|lwGj$mY^X;m6|ZgFC0`xoQ>jNhr8YJ;?z;YDeC!FOUZ>sl zaK6~@CE}D)m#DwoiJ2L}(}F$WL&D8S^!E!U!#HK)0ACk;NBC{ww}jsm{+{qP;Wvb@ z2)`zLS@>1qOTym}-WA>v-Vi<~d`kEQ;giBo3(pBZEIcbbE!-16Bz#bKzi_f%J&P9& zR8sHM<%aU85xk?=P)Xuf`B2IOHh!dkC$RBvam4O%4p`mIC)U|msdTtc)S%c~{>*CE znAy0}t0p_8b{+`zt51cTez;%6PrvxNxcF4KuP$FyCU4m<{U6xRklYB@V zNgGE&;y_)uF=81%wDTJe&cnuO{VcvIadg#(BYu>%`yb*lE6~g5!SN*RJT{(4US?ej zPlomRvhljHv9logZC>xgaxSRVLt(%8YuSAv>uC4emFuCIdRzF(cA?^Z{>=IPpPQTz z)dymK`9X~KW=|-U#NH+Kou@L+hf)bp%vhll+_Oq@G@9`p_$Vl4?I3#~>!Xh{9Z54| z#Fm4JS*eeJtoq}SQ=lAZbO#=2kAO@+2cVfV)Ab9z=@uKa&+cOr^+Wdu%!`Xx3i78# zW=uyVAm-?SY);&Fr^Rj;=K-^CYLUdH?(?lX>4)!D2(JYN6xnTF@-(meLE5TB`m0LD=)z zuC>auHC^)PqJ8KEs`2cpEA`r}$A_BNi)x`zX=_z#)*F7Y-o}WaStx4Xc=elwSN&FT zPM7>fvtHD#majXysEYM!wO;d0C?d~P3bQTS(P(O2Z3N;_EE?q!A}JMuf?uf@{h4w_ z*9ujwsIONr19&gS)?B@b;B6+wxk8hMexQm$N6i&#rHZ~^WIdlHptbK$x675FT=T2C+R{N(xN4hc46VjIW@=`70b3aRL-H zxpR8*h2h-=6#oyt^ZY(lK=>raJ_ByQO?x2o{z2V-5L)aUXgd77nm*zcT*La%nUnrM zDK$xa8W{J9*j=Tr5l@9U4*4g%5_AN^{|)xPA^0S&9Q=k}1&04P?r0_8*e$_tDm91k zvD<=wi13k1>`nypezGq3*GdKWv@#Ck5Bk?|7vvPg34Gc+{A@FSi{U@c+=+*9J;c2u z4&K8Y?+JcUsVnSHM=@oWUs{&0wGKJnAiKZn#2O#Fi2?UknA@L=Dqtv^| zC(#gli#vk<6|Q$e;!7P<>c_Y~SkI@%3zlDDOC+DzpwsU;IP2h?gC`w4 z<=}>cyAED*@Unwf9K7b>n-0G1;PuUz=Vx?1d0uY9o`bUv&N+C}!BY-yIJoQJB?m7% zc*VhM4!-H&+YVmejLqv8S%32#jbhKS$GH-%Ph!HsUv+TB!LK>^EsG!9v2DA`1iBNb zOjB1f$IqY25WN2z!TwMT?*y4jWueO715Nx`?A;Ky{5@oxKIq3)1{a#3Fs(AJ#j4>F zMDHqsK>tsTH86$0*WYf|lZ}6qi8k}1ih{Dm?m3x@4vNV3yrOCf^pNr99Hy;p{Z;_y z8spn(T28pIT~|f$z_)>Ho_72obVopTe%lWfTk=N8&EK;`G|bu)41+9o$Mc)SmJM0& zY3HY631r9j3_>A!H{_27Zbt-j&u*2!ji2)~f85zjv-2~5+(WjSe`h5$PrMWI-ZQ#> z^tsjicVzq&IOn%^(fP;f8xy8(T^MX`yH5*_&PP?WURQw4!6~*8X8)|$tFg7S^AG(O D-3+{G literal 0 HcmV?d00001 diff --git a/internal/ebpf/spike/execve_bpfel.go b/internal/ebpf/spike/execve_bpfel.go new file mode 100644 index 000000000..32e2de0f9 --- /dev/null +++ b/internal/ebpf/spike/execve_bpfel.go @@ -0,0 +1,136 @@ +// Code generated by bpf2go; DO NOT EDIT. +//go:build 386 || amd64 || arm || arm64 || loong64 || mips64le || mipsle || ppc64le || riscv64 || wasm + +package spike + +import ( + "bytes" + _ "embed" + "fmt" + "io" + + "github.com/cilium/ebpf" +) + +// loadExecve returns the embedded CollectionSpec for execve. +func loadExecve() (*ebpf.CollectionSpec, error) { + reader := bytes.NewReader(_ExecveBytes) + spec, err := ebpf.LoadCollectionSpecFromReader(reader) + if err != nil { + return nil, fmt.Errorf("can't load execve: %w", err) + } + + return spec, err +} + +// loadExecveObjects loads execve and converts it into a struct. +// +// The following types are suitable as obj argument: +// +// *execveObjects +// *execvePrograms +// *execveMaps +// +// See ebpf.CollectionSpec.LoadAndAssign documentation for details. +func loadExecveObjects(obj interface{}, opts *ebpf.CollectionOptions) error { + spec, err := loadExecve() + if err != nil { + return err + } + + return spec.LoadAndAssign(obj, opts) +} + +// execveSpecs contains maps and programs before they are loaded into the kernel. +// +// It can be passed ebpf.CollectionSpec.Assign. +type execveSpecs struct { + execveProgramSpecs + execveMapSpecs + execveVariableSpecs +} + +// execveProgramSpecs contains programs before they are loaded into the kernel. +// +// It can be passed ebpf.CollectionSpec.Assign. +type execveProgramSpecs struct { + HandleSchedProcessExec *ebpf.ProgramSpec `ebpf:"handle_sched_process_exec"` +} + +// execveMapSpecs contains maps before they are loaded into the kernel. +// +// It can be passed ebpf.CollectionSpec.Assign. +type execveMapSpecs struct { + DropCount *ebpf.MapSpec `ebpf:"drop_count"` + Events *ebpf.MapSpec `ebpf:"events"` +} + +// execveVariableSpecs contains global variables before they are loaded into the kernel. +// +// It can be passed ebpf.CollectionSpec.Assign. +type execveVariableSpecs struct { +} + +// execveObjects contains all objects after they have been loaded into the kernel. +// +// It can be passed to loadExecveObjects or ebpf.CollectionSpec.LoadAndAssign. +type execveObjects struct { + execvePrograms + execveMaps + execveVariables +} + +func (o *execveObjects) Close() error { + return _ExecveClose( + &o.execvePrograms, + &o.execveMaps, + ) +} + +// execveMaps contains all maps after they have been loaded into the kernel. +// +// It can be passed to loadExecveObjects or ebpf.CollectionSpec.LoadAndAssign. +type execveMaps struct { + DropCount *ebpf.Map `ebpf:"drop_count"` + Events *ebpf.Map `ebpf:"events"` +} + +func (m *execveMaps) Close() error { + return _ExecveClose( + m.DropCount, + m.Events, + ) +} + +// execveVariables contains all global variables after they have been loaded into the kernel. +// +// It can be passed to loadExecveObjects or ebpf.CollectionSpec.LoadAndAssign. +type execveVariables struct { +} + +// execvePrograms contains all programs after they have been loaded into the kernel. +// +// It can be passed to loadExecveObjects or ebpf.CollectionSpec.LoadAndAssign. +type execvePrograms struct { + HandleSchedProcessExec *ebpf.Program `ebpf:"handle_sched_process_exec"` +} + +func (p *execvePrograms) Close() error { + return _ExecveClose( + p.HandleSchedProcessExec, + ) +} + +func _ExecveClose(closers ...io.Closer) error { + for _, closer := range closers { + if err := closer.Close(); err != nil { + return err + } + } + return nil +} + +// Do not access this directly. +// +//go:embed execve_bpfel.o +var _ExecveBytes []byte diff --git a/internal/ebpf/spike/execve_bpfel.o b/internal/ebpf/spike/execve_bpfel.o new file mode 100644 index 0000000000000000000000000000000000000000..82e5ffdd82d99f009b0e2c087bc43a57cb68ce6d GIT binary patch literal 6960 zcmbtYTWp+16&_#WTb$Urk(3hphc;%NI-5;e+9+wG&BY;6O|g;yDXR2)y*suS?~UDm zQ@d$}C4y2_eXs;b0TtmwC4$6*9}vl#{lG&I7X=BSNbnGNia)#VQ zC}QmMpYxqLbLN~g^Uu!i*9M2qHa9gX*P7Hn)hcpYrIvQD%4s8})fQMTe9Y=^by&W~ z8+@x-siV-{YO(#_0Q)*{4$V!&?Bv zf9N$(ZBlO<;p+7i)#~c?gz!MP^?3Dquiy^h#trP3W&D!x2g2_QzbE{z@H@g6h2IuF zFZ`zPIpH^i&kBD>_>Ax=;T7Q%!bgN(7CtQeoba^pqry|d6T$=GdxZB2?+|X7a`nv0 zdb8e}Kv&xXV?ewWlx=S{_zgS*gRLL-_ZV#bJG^SQ6TMjHuNtP>QGG_peZmp6cl>F{ z3)ZcPi*^g#JZL>TEMNG*a{A$Zp&t&RA5Jm-f!$YEciX&~ANwEM&kwDiT`e{s`e6kg z6$krW92totySp1&HJLJlsG!JH~dg=c8?#AU8hDqkBEo)xOrSW zt9jXV&17tSzJ&Z%@J9E@`4C_4qwvFZ;v2V+1xKU58pzq1e$ih8zXf9Zwq@!}JyQri zcmC3$&khfX>ap1O|Jr2g&p{nXjC853;i9<(BEn;9V%|XmDt0M`PyLgiO&~O9XAw+R z-K`x%TN=SfE35y6Q-FUGM1N_}0T9|&9+eUcakD)!DX#U)n4~q^U1rdlc;kNf9v`*? zI{40hMr6ix+{zE-#9enz?Dz^w@jJNs7p%UCJ0NXk)~Gdr%p5yK#~e3<(jX1m0-6Ek zLEAu!pfU(;>n=RvF>`zJghx$UIp_C4^v(8T(8ocH|7Rl8{+A%uCII~&#Jtm>zks-Y zBcQ*DJOlm@5Ly$*(AOp#fccbUZaXaQU_Tq+7RpaR;IX+E9RJ;)fP5F#$C%bMWX|Wt z{1JM}0q9SVp8`*VJ`#Bb^1mSm;ESME6!KHx#xZ2BLmHDj3HcewGmxbEpZC)!NUR=z7t;4Coe%I$2D2 z2sW@aHqX)kjlN8fW@`cDOOXo0lNTy{mrPqcB!%#)j6|IVysZf`qYF^ir zz5=PH>dzg4J)iYbEk9n;xqvR}FFa2*o(*-OTpADfP?LIEUC9*cTIH(cN|-IzF(RsF zvN|+g!)oS@u$G>M5O7*>bU1E`=r(k;e*|@tW(XRJATvB5^1dm3$77 zBf?hAOsB*}} zYoA`!hZy`7ogA%FO1o z=(FoH5Y+N->hf6PfbJg%QvJtOXMQY5?9=_hRh2ztjgk|p6Dt^CUEnPR8?z+hxtOV- za^=Z-CDa97O!TcT+Cb2UF%73?6k-a)+H?t})=_pMM9soXE|)N!1HoZhhv8^FUx@Oh zu&9eQ9VIkki-$@heelF&zLY~07l+TkG8hhiaq!hk;o#-L)3!6p7j-Sl6f0q=CZSGJ z7mn))s)PxP!&x5cvh`{edzLF6M&tRMvA`_Auu7l;{rQ~uMmKbLoH!9Ycf=~|M(2Bj zHjFv512;5k`138eTd`;dPf%!-LU2EGi88fG#_6^QU?}o|e%~F9nIE}WDdw!II#UQM z85Tl~SIbz`g3jc0)plg7I;ToCymeF43dOBP;b^%Wv8?7LQ|66G9ecqn&sqb-c53)+ zc>41f2Ez-3C(k4}H!@k{1tF!59Z{V&f(?emVl<104QuWDG5E0RM8S}^-e9mAgu4!sXeNuL7& zdXgA#f;;TYF@6Jc^oV)q7*DORJT?YXy!r=EtaGRZeL-q!3=P|bI|A!Cs&OP_a^a+| zmUMwz!R#`3490hw)8U{WS6n6vArN=?C@_(kBh+e*D7_zZCKqEa`+ zpC-;Jbq}_j?_G|cQ0l(m9|7+~0uN$%JMfa=-=M!evT<@rS@$<`BP!Q!%_5{g(y* z7WSPVDpm3Dl;D5S|4pTC3O-Rj;4R1>Hj@3s43!!|EC zD|lJ(oZzF#h4#M|JOjKR_&8!?yCe83f~|J_XN!Wd*G>U%kLjmm9^T`(DMoBtukfAV z)H@uAp5JG;xo?n=c@JfCb|}A@WrRvJVot@iVxvs)?=ehWx5Pun6bC?T#PpE{u{k_! zVFQnNxZ>d%56^md&cpK_Ui9!?58wCjl7~$a(7E{SuX(FDV3M)^l!wzE9`^8vhbtbQ z@$jsN=R7>`;YAPM_3(WUFL{_}XFR`N5A$q{_oqCZ_VBQWM?75d@QjCNJv`^(c@Hmo z_^yZVdw9vi?$v9oe{BD=RDp+I^6-#{U-xjq!*6-`Jr8f*+Py_3BRv(VWK|cEr!JjM z60Ckla9Sf0!e0mH?@(#M zj@^*olLJw7gELPzzE||ez&XEPgWD3QJHN%;*gBcK547I+J2E~MH-_xycj{Rg@37;` zGCqp^ILJP~e(yoIUjDZwe>Xq#=kJbgewROgw`2T%E0|wXlzQJQj6Xkpt~dV!nSVsa xbAH/dev/null 2>&1; then + echo "clang is required to regenerate eBPF objects" >&2 + exit 1 +fi + +case "$(uname -m)" in + x86_64|amd64) export BPF_TARGET_ARCH=x86 ;; + aarch64|arm64) export BPF_TARGET_ARCH=arm64 ;; + *) + echo "unsupported architecture: $(uname -m)" >&2 + exit 1 + ;; +esac + +CLANG_VERSION="$(clang --version | head -n1)" +echo "clang: ${CLANG_VERSION}" +echo "target arch: ${BPF_TARGET_ARCH}" + +go run github.com/cilium/ebpf/cmd/bpf2go@v0.20.0 \ + -go-package spike -output-dir . -cc clang -target bpfel,bpfeb \ + execve ./c/execve.bpf.c -- -I./c -O2 -g "-D__TARGET_ARCH_${BPF_TARGET_ARCH}" + +go run github.com/cilium/ebpf/cmd/bpf2go@v0.20.0 \ + -go-package spike -output-dir . -cc clang -target bpfel,bpfeb \ + prociter ./c/proc_iter.bpf.c -- -I./c -O2 -g "-D__TARGET_ARCH_${BPF_TARGET_ARCH}" + +echo "generated spike bpf bindings" diff --git a/internal/ebpf/spike/prociter_bpfeb.go b/internal/ebpf/spike/prociter_bpfeb.go new file mode 100644 index 000000000..e9b72e1a1 --- /dev/null +++ b/internal/ebpf/spike/prociter_bpfeb.go @@ -0,0 +1,136 @@ +// Code generated by bpf2go; DO NOT EDIT. +//go:build mips || mips64 || ppc64 || s390x + +package spike + +import ( + "bytes" + _ "embed" + "fmt" + "io" + + "github.com/cilium/ebpf" +) + +// loadProciter returns the embedded CollectionSpec for prociter. +func loadProciter() (*ebpf.CollectionSpec, error) { + reader := bytes.NewReader(_ProciterBytes) + spec, err := ebpf.LoadCollectionSpecFromReader(reader) + if err != nil { + return nil, fmt.Errorf("can't load prociter: %w", err) + } + + return spec, err +} + +// loadProciterObjects loads prociter and converts it into a struct. +// +// The following types are suitable as obj argument: +// +// *prociterObjects +// *prociterPrograms +// *prociterMaps +// +// See ebpf.CollectionSpec.LoadAndAssign documentation for details. +func loadProciterObjects(obj interface{}, opts *ebpf.CollectionOptions) error { + spec, err := loadProciter() + if err != nil { + return err + } + + return spec.LoadAndAssign(obj, opts) +} + +// prociterSpecs contains maps and programs before they are loaded into the kernel. +// +// It can be passed ebpf.CollectionSpec.Assign. +type prociterSpecs struct { + prociterProgramSpecs + prociterMapSpecs + prociterVariableSpecs +} + +// prociterProgramSpecs contains programs before they are loaded into the kernel. +// +// It can be passed ebpf.CollectionSpec.Assign. +type prociterProgramSpecs struct { + DumpTask *ebpf.ProgramSpec `ebpf:"dump_task"` +} + +// prociterMapSpecs contains maps before they are loaded into the kernel. +// +// It can be passed ebpf.CollectionSpec.Assign. +type prociterMapSpecs struct { + DropCount *ebpf.MapSpec `ebpf:"drop_count"` + Events *ebpf.MapSpec `ebpf:"events"` +} + +// prociterVariableSpecs contains global variables before they are loaded into the kernel. +// +// It can be passed ebpf.CollectionSpec.Assign. +type prociterVariableSpecs struct { +} + +// prociterObjects contains all objects after they have been loaded into the kernel. +// +// It can be passed to loadProciterObjects or ebpf.CollectionSpec.LoadAndAssign. +type prociterObjects struct { + prociterPrograms + prociterMaps + prociterVariables +} + +func (o *prociterObjects) Close() error { + return _ProciterClose( + &o.prociterPrograms, + &o.prociterMaps, + ) +} + +// prociterMaps contains all maps after they have been loaded into the kernel. +// +// It can be passed to loadProciterObjects or ebpf.CollectionSpec.LoadAndAssign. +type prociterMaps struct { + DropCount *ebpf.Map `ebpf:"drop_count"` + Events *ebpf.Map `ebpf:"events"` +} + +func (m *prociterMaps) Close() error { + return _ProciterClose( + m.DropCount, + m.Events, + ) +} + +// prociterVariables contains all global variables after they have been loaded into the kernel. +// +// It can be passed to loadProciterObjects or ebpf.CollectionSpec.LoadAndAssign. +type prociterVariables struct { +} + +// prociterPrograms contains all programs after they have been loaded into the kernel. +// +// It can be passed to loadProciterObjects or ebpf.CollectionSpec.LoadAndAssign. +type prociterPrograms struct { + DumpTask *ebpf.Program `ebpf:"dump_task"` +} + +func (p *prociterPrograms) Close() error { + return _ProciterClose( + p.DumpTask, + ) +} + +func _ProciterClose(closers ...io.Closer) error { + for _, closer := range closers { + if err := closer.Close(); err != nil { + return err + } + } + return nil +} + +// Do not access this directly. +// +//go:embed prociter_bpfeb.o +var _ProciterBytes []byte diff --git a/internal/ebpf/spike/prociter_bpfeb.o b/internal/ebpf/spike/prociter_bpfeb.o new file mode 100644 index 0000000000000000000000000000000000000000..4547f4feb0b2bbf61e29f83d13ecd0fe0dfda9f2 GIT binary patch literal 5592 zcmbtXU2I%O6+U~{X=CzZH#EdRp*OUcb>wU|C4}Or(T3I`5hk_b6r~mD`g(n1FWx_P z??!fA#3G6a5<-^vsU?t_iU)!y!a|j7i9(D75>oqMBp#6HgC7v8Xdi+Eq7RYG_syKU zz8=*=h>^~G=R0%GnVB<>sY;^ZC0 zJBn{AZYus+aYOMBitCDNiYtn@6mKdnD=sPCQ0yqqD>f8o6(<$1Dvm2&P%J7ws#s9W zDf)^7iv5av6$wc_y;5kXXubC=PKr-UY1TduKy&^JN5tk2#pKoVDBS*-jqf{Zap91S zTMWgl3vqURp^XPO>p0vm9wWm0Y<{d`KRL!tevF%WL(N;760?t#|NZp8{XX{Ck8dE^ z$MdU}%J&tYXonU5a~H3i_{{j2n*Jwv>%|QH&Dun=YgT$pF0&CBFrG19B0WH#0W@l( z8~5}<$ezRxx(~6%5V?oC8>7AqW)9Zj{gA}`Vd(fdND*@EAUd>rA!c0HW`28aUig?{ z^)dB-7oT(i1sgW2*D~E^7=;MF{tp#B-0m zw4rg2`yfR~1UUfdK+2H&AnTC2?j5g;9ed}QJ&UB=CfE5b2y?T22l4?(5n>zw$5Z-; zsADoNlkwk$9D%%mV$sI4+(hnV{cnTQkL?bGx)1pmMCUP&2=xw9aLL@;I&`knw`ns# zLESP%$O-5l0d{~%@&~D#Llt=_Wgmv$DJ~3+6PZ${&h#kkST5_3{Q;Cj{~>G-L(sA> zq8o(x(0>f1y$JmlkoHOFKSv;^0c2kReiVY1T{9DkU|-qaI6nHO$o_uY2VORieX=%` zyCQtiAUJpV^0}vj ziHpyS23MXQ9}NPD7aEaN!}%bp#m#cmlIS|Lmb5?q2>jW%YpwE3Et>Y3qJ8=l&FH)4 zO1(DYvy-`KL9U0Db|llydLt;++lZKITnox^)C__+Y|TkEibFA4DV~?OC~Ol1o@Kma?F3sN7V7N)Xzw7`I?_QN`1&=3|eusU5ceqo|bq9T{8+R zK_hHpLo(B>w;Mqv3a6u{9Vj)UX{og^(foq6;;eVW~31L$TBL(S2 zMoi6_j-Q2&shPiPBGKj0^C(BTYlC@!)U;A85lnX4f-Rj z6dyS2fI_kc4PC1V!gFc%P#8IdL&DRwGYc)6gQ_`WK7wsLsfd$^NS&Tj?zlOoUeLHCuHL~hW(pu8>eJ@QHAKM`3bpGE91A-@*6 zMcz^Vn#e2stSl?XU44z?w=DPYJznQ~cnyO2J>2472G6{s9P3#@ym?h~yn%eIh3?02 zeAhhPkM{z~Lx0_mhk4d8hp8Lme}(x_D=(+{$(iqh^1qAx4wHGamS^GjI_?9UhwICZ zifmy0-n{b5C@Jm-UMIzIukdatN8B5I;7iJJSJ-6yvhqKQ{1x9E?`Dc~{kN3=L*z}4 zucSD~*DUYBT>s>HH`mHaKscki=sdY92*JOGZ}+l1eP zI5^aLM`K;?Pua=Yd`JuSJtV2ddm$TZz&Ti3whjc>k%VWz4V~k(p=G&8>Iq+g&fLlc z_bL;c@S?-V9X{#shQm7!Uvl_OhjTsLOEUku!#5nh>F_%{xhYF3U#8y~_Z?nvc+uhG z4xe;*!{Hr=FFE|C!&e->?(hwVZ#w+WPHx^$sr{SxQJVXXf5G8n4*!C~`P)h7d(Po} z{?g+=a`?**f7RiyJNylYzn$=X2lpS4d>qZkl5a+p{HL#+&y#Fli;@ej{laZuKl5HF5dveh2foVaDN<gE~d`vx#N=-|ZP>aNZY5&O;BVwwPEHS=*#h zPq_PjDJD)1CciV9MO@qDh?60}VJH!7(C)AYIXt^GcS0j7j{G`3L?3MR%I9 literal 0 HcmV?d00001 diff --git a/internal/ebpf/spike/prociter_bpfel.go b/internal/ebpf/spike/prociter_bpfel.go new file mode 100644 index 000000000..69633c0fe --- /dev/null +++ b/internal/ebpf/spike/prociter_bpfel.go @@ -0,0 +1,136 @@ +// Code generated by bpf2go; DO NOT EDIT. +//go:build 386 || amd64 || arm || arm64 || loong64 || mips64le || mipsle || ppc64le || riscv64 || wasm + +package spike + +import ( + "bytes" + _ "embed" + "fmt" + "io" + + "github.com/cilium/ebpf" +) + +// loadProciter returns the embedded CollectionSpec for prociter. +func loadProciter() (*ebpf.CollectionSpec, error) { + reader := bytes.NewReader(_ProciterBytes) + spec, err := ebpf.LoadCollectionSpecFromReader(reader) + if err != nil { + return nil, fmt.Errorf("can't load prociter: %w", err) + } + + return spec, err +} + +// loadProciterObjects loads prociter and converts it into a struct. +// +// The following types are suitable as obj argument: +// +// *prociterObjects +// *prociterPrograms +// *prociterMaps +// +// See ebpf.CollectionSpec.LoadAndAssign documentation for details. +func loadProciterObjects(obj interface{}, opts *ebpf.CollectionOptions) error { + spec, err := loadProciter() + if err != nil { + return err + } + + return spec.LoadAndAssign(obj, opts) +} + +// prociterSpecs contains maps and programs before they are loaded into the kernel. +// +// It can be passed ebpf.CollectionSpec.Assign. +type prociterSpecs struct { + prociterProgramSpecs + prociterMapSpecs + prociterVariableSpecs +} + +// prociterProgramSpecs contains programs before they are loaded into the kernel. +// +// It can be passed ebpf.CollectionSpec.Assign. +type prociterProgramSpecs struct { + DumpTask *ebpf.ProgramSpec `ebpf:"dump_task"` +} + +// prociterMapSpecs contains maps before they are loaded into the kernel. +// +// It can be passed ebpf.CollectionSpec.Assign. +type prociterMapSpecs struct { + DropCount *ebpf.MapSpec `ebpf:"drop_count"` + Events *ebpf.MapSpec `ebpf:"events"` +} + +// prociterVariableSpecs contains global variables before they are loaded into the kernel. +// +// It can be passed ebpf.CollectionSpec.Assign. +type prociterVariableSpecs struct { +} + +// prociterObjects contains all objects after they have been loaded into the kernel. +// +// It can be passed to loadProciterObjects or ebpf.CollectionSpec.LoadAndAssign. +type prociterObjects struct { + prociterPrograms + prociterMaps + prociterVariables +} + +func (o *prociterObjects) Close() error { + return _ProciterClose( + &o.prociterPrograms, + &o.prociterMaps, + ) +} + +// prociterMaps contains all maps after they have been loaded into the kernel. +// +// It can be passed to loadProciterObjects or ebpf.CollectionSpec.LoadAndAssign. +type prociterMaps struct { + DropCount *ebpf.Map `ebpf:"drop_count"` + Events *ebpf.Map `ebpf:"events"` +} + +func (m *prociterMaps) Close() error { + return _ProciterClose( + m.DropCount, + m.Events, + ) +} + +// prociterVariables contains all global variables after they have been loaded into the kernel. +// +// It can be passed to loadProciterObjects or ebpf.CollectionSpec.LoadAndAssign. +type prociterVariables struct { +} + +// prociterPrograms contains all programs after they have been loaded into the kernel. +// +// It can be passed to loadProciterObjects or ebpf.CollectionSpec.LoadAndAssign. +type prociterPrograms struct { + DumpTask *ebpf.Program `ebpf:"dump_task"` +} + +func (p *prociterPrograms) Close() error { + return _ProciterClose( + p.DumpTask, + ) +} + +func _ProciterClose(closers ...io.Closer) error { + for _, closer := range closers { + if err := closer.Close(); err != nil { + return err + } + } + return nil +} + +// Do not access this directly. +// +//go:embed prociter_bpfel.o +var _ProciterBytes []byte diff --git a/internal/ebpf/spike/prociter_bpfel.o b/internal/ebpf/spike/prociter_bpfel.o new file mode 100644 index 0000000000000000000000000000000000000000..08f210f72086884e00bf034626a41c3940f8eefd GIT binary patch literal 5592 zcmbtXU2I%O6+U)c$95e5gxEC@;D#2nj_l2*gisvS+R!>A!X#GgqO<~Cuh%#B;{EgP z-N;)PVTn?uQiUuP(g=_m-~me%VWCQnL?K2338{TBQXi1$gC7v8Xdi+Eq7RnL_syKU zyPgIl#F5VZ&Ufa_nVBIe@UH1UXfcz>UPqYNjZ$j>Vs{D^&Pxw zFtuzzQcEqy_}aje1~=QSf51t;*(~xXe47Vs`?mq#g5GVl{K?i1W2C>oyGP^hkFEb8 z`t9!R?Ya5bpF{M?c@ww^LjLC-L*)T^+!!l26LibU&6uL6Xfv+d>`~sPXwo45eeHiw z@g2n-#Xl)-EB--oOYx54hT^*7ZN*!PYl=4%R~45Pi;4@1Gm2LgClxO!CKVr5Oen?_ zJ;edV9>q3A1HyWu^pftkob`SHy3*E@cdD@ zj_078B#`e}kS8jstoP-M(qw_Bs72?hOR<0&|c^kv;c*4_2JSuXYScEP^{I|?giM)P5BP=BhVyNrFkT> z(B)%lBi~{4mzSUqLSKf$*U7!yfnxqGN#J`>#!>D;X?xIrLZfl`h^D;??Sjqy+k*0G zsRj#M9l|bf7g`%G>RM2C#c+Jm*LCN>SRC!TyL6{O_rNd>JtK^E- z&ybVGpBOzQ>667$A#M7_kszLycD8wsdFVAVM*FO^XRdj%Hrfl5I$rf;q{TG0<{V%3-P$`m=>X7-n*Tqzk#6q!&^p zNsK0>9T_n+M;aM}jiH&p<|5JQF!DG;;Te+l03lp|DU+X{tpI~^P`Vz(25pgty>jN6 zpl~gAA{ZL>5<}6Ff+24OC9py91!>1NcqlHiB@koks+n^sEUHjg#M**vkc$o0D?jWF zqE9WU>4iD@ez}@Y``3anz2K+vbAD=WE@m2sy;F?#{n<(;8)ou;F36RGFcx5LjZ8_Hh`5xU9rRYvQBrAK7T$4;fiUVsFb#d zNNlTZ>YNxoW5(LQJxFHvV!!(=HtTcF{L{rMsy#Bs4IS2A*4EN%+Yly`7<~j=ZH`NA zgoY!8Me)Gd02GonDC%5IC!9;OhQ#P;Y!Xh_{w(xp4w`0O^1a%DD`v0ID^d_yKKK0bbF zYFy$tSY^p((m}o))bC+)_ww7o;{yi5_Zqbm4=fM*I&40(egwty$;dHW`TU~KgHnD0 z{VlXBYvak^g0>cIEcs(d(6x$Z8f@~*;N8#J9OP;6)*JS_jJ!hrU6C2ss5@EgjDXzzYoWKH=C?7xG0DE}jP|6fFIH}DSdb>)9&`#T~V z4ZH*Vj`Bk-nD0MCwv`WpH|^HX0>5!61JIut%eL`5B?fJ8MNAeg7tu{}o8N z>TuSI@egCJ6xOCOA8SFL)poA^A@DbpbFJj>Du?+W<$(Q+-Pg`1MIy~#} zXC3~c!++@TR~`Pk!{2oH+YW!v;fK094@*1@mP3h`f^7T?)92$P_0OW{1J}Oc>K~vC zuYZKbv)Su8ej1hV@mqTj#_@$2re-BxuI3Et5VhB)E#CieeHwlBmfV-+7=Mr;D;8>3 z-R^yyzWS5JHYIBj`wi}Uql|+5xBk)dE9%o08H#6s{Etm4kHGvugLvxb1ah5G{~q=8 zADQF3HSp9CJ@+)+#6~ue|8n>1pV0n^#$edd_>nuW{UaXXjP^g~ba3nUb#%Dj`eWTT zQ#3x;&mXfWU9^6_6FGlZp4FG-uAcX(-5sAf?>GKc9e+#vb9~0R<39o4fr-5WU=>=E h0X={2c= 0 { + b = b[:i] + } + return string(b) +} + +func execLookPath() string { + for _, p := range []string{"/bin/true", "/usr/bin/true"} { + if _, err := os.Stat(p); err == nil { + return p + } + } + return "/bin/sh" +} + +func runTrueOnce() { + cmd := execLookPath() + p, err := os.StartProcess(cmd, []string{cmd}, &os.ProcAttr{ + Files: []*os.File{nil, nil, nil}, + }) + if err != nil { + return + } + _, _ = p.Wait() +} From 795872657bd973218db0eefb62089b1b1416fe9b Mon Sep 17 00:00:00 2001 From: Mostafa Moradian Date: Wed, 5 Aug 2026 21:41:07 +0200 Subject: [PATCH 04/28] docs(ebpf): Document Linux eBPF feasibility and build gating worklist Record validated runtime/tooling prerequisites, spike proofs, Windows coupling hotspots, and the ps.Snapshotter consumer migration needed for a Linux build. --- internal/ebpf/FEASIBILITY.md | 96 ++++++++++++++++++++++++++++++++++++ 1 file changed, 96 insertions(+) create mode 100644 internal/ebpf/FEASIBILITY.md diff --git a/internal/ebpf/FEASIBILITY.md b/internal/ebpf/FEASIBILITY.md new file mode 100644 index 000000000..c37217e7e --- /dev/null +++ b/internal/ebpf/FEASIBILITY.md @@ -0,0 +1,96 @@ +# Linux eBPF Feasibility Notes + +This note records the runtime contract, tooling, and build-gating work validated by the throwaway spike under `internal/ebpf/spike`. + +## Runtime contract + +Hard requirements (no graceful degradation): + +- Linux kernel >= 5.9 (BPF task iterators) +- Usable runtime kernel BTF at `/sys/kernel/btf/vmlinux` +- Ring buffer maps and helpers +- Tracing programs with `iter/task` attach support +- Capabilities: `CAP_BPF`, `CAP_PERFMON`, and `CAP_SYS_PTRACE` for best-effort `/proc` enrichment + +Explicit non-fallbacks: + +- No BTFHub download +- No embedded build-host BTF as a runtime substitute for iterator attach +- No `bpf_d_path` (helper starts in 5.10; executable path comes from best-effort `/proc//exe`) + +`internal/ebpf.ProbePrerequisites` encodes these checks and fails with actionable errors. + +## Tooling + +| Tool | Pin / note | +| --- | --- | +| `github.com/cilium/ebpf` | v0.20.0 | +| `bpf2go` | version-matched to cilium/ebpf v0.20.0 | +| clang/LLVM | Spike objects regenerated with Debian clang 19.1.7 (`golang:1.26` image) | +| bpftool | Optional for inspecting BTF; not required for ordinary builds | +| Host requirements for spike runs | Privileged Linux, `/sys/kernel/btf/vmlinux`, mounted `tracefs` (`/sys/kernel/tracing`) | + +Regenerate spike objects with `internal/ebpf/spike/generate.sh`. Ordinary `go build` consumes committed generated bindings and does not require clang. + +## Spike proofs + +The spike under `internal/ebpf/spike` demonstrates: + +1. CO-RE load of a `sched/sched_process_exec` tracepoint program that emits to a ring buffer +2. `iter/task` attachment and scan without `bpf_d_path` +3. Shared canonical maps across separately generated collections via `CollectionOptions.MapReplacements` +4. Race-safe startup prototype: start ringbuf reader, attach hot path, queue hot events, run iterator baseline keyed by `ProcessKey{PID,StartBootTime}`, replay pending events idempotently, then switch live +5. Best-effort `/proc//{exe,cmdline}` enrichment that never replaces the iterator scan +6. Drop accounting for ringbuf reserve failures and bounded pending-queue pressure + +Validated on Docker Desktop LinuxKit 6.12.76 (arm64) with privileged containers, mounted kernel BTF, and mounted tracefs. Example spike metrics: hot events queued during baseline and replayed (`pending_queued`/`replay_applied` > 0), ringbuf drops at zero under light load. Task-iterator snapshot counts reflect processes visible in the container PID namespace. + +Run (privileged Linux host or container with kernel BTF mounted): + +```bash +go test ./internal/ebpf -count=1 +cd internal/ebpf/spike && ./generate.sh +go run ./internal/ebpf/spike/cmd/spike +``` + +## Windows coupling audit + +Unguarded Windows imports that block a clean `GOOS=linux` build include (non-exhaustive; prioritize bootstrap and shared packages): + +- `internal/bootstrap/bootstrap.go` (`golang.org/x/sys/windows`, `pkg/handle`) +- `internal/bootstrap/source.go` (hard-wires `etw.NewEventSource`) +- `cmd/fibratus/app/root.go` (runtime reject of non-Windows) +- Shared packages importing `golang.org/x/sys/windows` without build tags, notably: `pkg/event/enum.go`, `pkg/event/flags.go`, `pkg/config/output.go`, `pkg/filter/ql/function.go`, `pkg/util/log/logger.go`, `pkg/util/signals/signals.go`, `pkg/callstack/callstack.go`, `pkg/pe/parser.go`, `pkg/fs/*`, many `pkg/sys/*`, `pkg/handle/*` + +Already Windows-tagged or stubbed in places: `pkg/config/eventsource.go`, `pkg/event/types_windows.go`, `pkg/ps/types/types_windows.go`, `pkg/yara/scanner_unsupported.go`, `pkg/cap/writer_unsupported.go`, `pkg/filament/filament_unsupported.go`. + +## `ps.Snapshotter` consumer audit + +Current interface methods used by Windows (full contract in `pkg/ps/snapshotter.go`): `Write`, `AddThread`, `AddModule`, `RemoveThread`, `RemoveModule`, `AddMmap`, `RemoveMmap`, `WriteFromCapture`, `Remove`, `Find`, `FindModule`, `FindAllModules`, `FindAndPut`, `Put`, `Size`, `Close`. + +| Consumer | Needs on Linux | Migration | +| --- | --- | --- | +| `pkg/rules/engine.go` | `Find` only | Move to narrow `ps.Resolver` | +| `pkg/rules/compiler.go` | `Find` only | Move to `ps.Resolver` | +| `pkg/rules/sequence.go` | `Find` only | Move to `ps.Resolver` | +| `internal/bootstrap/*` | Construct platform snapshotter | Split `_windows` / `_linux` | +| `internal/etw/*` processors | Full Windows snapshotter | Keep Windows-only | +| `pkg/symbolize/*` | Modules / PE paths | Gate Windows-only; stub or omit on Linux | +| `pkg/yara/scanner.go` | Process memory context | Keep unsupported on Linux for now | +| `pkg/cap/*` | Capture restore | Out of initial Linux scope; keep stubs | +| `pkg/filament/*` | Process state for filaments | Out of initial Linux scope; keep stubs | +| `pkg/filter/filter_windows.go` | Optional psnap option | Linux filter path uses Linux accessors | + +Recommended Linux contract: `ps.LinuxSnapshotter` with `Write`, `Remove`, `UpsertSnapshot`, `Find`, `Put`, `Size`, `Close`, plus thread/mmap state. Shared rules/sequence code must depend only on `ps.Resolver` (`Find`). + +## Build gating worklist + +Work required before a Linux process event source can land: + +1. Build-tag split `internal/bootstrap` and replace ETW hard-wire with Linux eBPF source selection +2. Add `cmd/fibratus/main_linux.go` and per-OS command registration in `cmd/fibratus/app` +3. Add Linux `event.Type` semantic IDs (`uint16`, not syscall numbers) and `pkg/config/eventsource_linux.go` +4. Introduce `ps.Resolver` and migrate rules/compiler/sequence consumers +5. Add Linux PS types and `ProcessKey{PID,StartBootTime}` +6. Gate or stub remaining untagged Windows imports on the Linux build graph +7. Promote spike loader/consumer patterns into production `internal/ebpf` packages with committed generated objects and CI generation-drift checks From 05a796b21eca017bb1ef463033f7a0a77596a5a5 Mon Sep 17 00:00:00 2001 From: Mostafa Moradian Date: Wed, 5 Aug 2026 21:45:05 +0200 Subject: [PATCH 05/28] fix(ebpf): Harden spike reconciler ownership and shutdown paths Ignore late iterator snapshots after live switch, avoid double-closing MapReplacement-owned maps, and back off on persistent ringbuf read errors. --- internal/ebpf/FEASIBILITY.md | 2 +- internal/ebpf/features.go | 4 +++- internal/ebpf/reconcile.go | 5 +++++ internal/ebpf/reconcile_test.go | 17 +++++++++++++++++ internal/ebpf/spike/run.go | 9 +++++++-- 5 files changed, 33 insertions(+), 4 deletions(-) diff --git a/internal/ebpf/FEASIBILITY.md b/internal/ebpf/FEASIBILITY.md index c37217e7e..f9344b3ba 100644 --- a/internal/ebpf/FEASIBILITY.md +++ b/internal/ebpf/FEASIBILITY.md @@ -9,7 +9,7 @@ Hard requirements (no graceful degradation): - Linux kernel >= 5.9 (BPF task iterators) - Usable runtime kernel BTF at `/sys/kernel/btf/vmlinux` - Ring buffer maps and helpers -- Tracing programs with `iter/task` attach support +- Tracing programs plus runtime kernel BTF (required for `iter/task`; attach is verified when the spike/loader calls `AttachIter`) - Capabilities: `CAP_BPF`, `CAP_PERFMON`, and `CAP_SYS_PTRACE` for best-effort `/proc` enrichment Explicit non-fallbacks: diff --git a/internal/ebpf/features.go b/internal/ebpf/features.go index 8ef430124..ea9ecf695 100644 --- a/internal/ebpf/features.go +++ b/internal/ebpf/features.go @@ -103,7 +103,9 @@ func ProbePrerequisites() (*PrerequisiteReport, error) { report.RingbufHelper = true } - // Task iterators attach as Tracing + AttachTraceIter against a kernel BTF target. + // iter/task attach still needs a loaded program; ProbePrerequisites only checks + // the necessary Tracing + runtime BTF preconditions. AttachIter in the spike + // (and later loader) is the conclusive probe. if report.TracingOK && report.BTFOK { report.IterOK = true } else { diff --git a/internal/ebpf/reconcile.go b/internal/ebpf/reconcile.go index 31184d0d6..2d939c981 100644 --- a/internal/ebpf/reconcile.go +++ b/internal/ebpf/reconcile.go @@ -105,9 +105,14 @@ func (r *StartupReconciler) EnqueueHot(ev HotEvent) bool { } // UpsertSnapshot installs an iterator baseline record keyed by ProcessKey. +// After FinishBaseline, late snapshot records are ignored so they cannot +// overwrite live hot-path state. func (r *StartupReconciler) UpsertSnapshot(rec ProcessRecord) { r.mu.Lock() defer r.mu.Unlock() + if r.live { + return + } rec.FromSnap = true existing, ok := r.procs[rec.Key] if !ok { diff --git a/internal/ebpf/reconcile_test.go b/internal/ebpf/reconcile_test.go index 3e8c7031a..516bf078e 100644 --- a/internal/ebpf/reconcile_test.go +++ b/internal/ebpf/reconcile_test.go @@ -68,6 +68,23 @@ func TestStartupReconcilerRaceSafeBaseline(t *testing.T) { } } +func TestStartupReconcilerIgnoresLateSnapshots(t *testing.T) { + r := NewStartupReconciler(8) + key := ProcessKey{PID: 7, StartBootTime: 9} + r.UpsertSnapshot(ProcessRecord{Key: key, Comm: "snap"}) + r.FinishBaseline() + r.EnqueueHot(HotEvent{Key: key, Kind: 1, Comm: "live", ExePath: "/bin/live"}) + r.UpsertSnapshot(ProcessRecord{Key: key, Comm: "stale-snap", ExePath: "/bin/stale"}) + + got, ok := r.Get(key) + if !ok { + t.Fatal("missing process after late snapshot") + } + if got.Comm != "live" || got.ExePath != "/bin/live" { + t.Fatalf("late snapshot overwrote live state: %+v", got) + } +} + func TestStartupReconcilerPendingBackpressure(t *testing.T) { r := NewStartupReconciler(2) key := ProcessKey{PID: 1, StartBootTime: 1} diff --git a/internal/ebpf/spike/run.go b/internal/ebpf/spike/run.go index 44293e76e..6ba8aff9c 100644 --- a/internal/ebpf/spike/run.go +++ b/internal/ebpf/spike/run.go @@ -79,6 +79,7 @@ func Run(duration time.Duration) (*Result, error) { defer execObjs.Close() // Inject the canonical shared maps from the first collection into the second. + // The first collection owns those maps; only close the iterator program here. var iterObjs prociterObjects if err := iterSpec.LoadAndAssign(&iterObjs, &ebpf.CollectionOptions{ MapReplacements: map[string]*ebpf.Map{ @@ -88,7 +89,11 @@ func Run(duration time.Duration) (*Result, error) { }); err != nil { return nil, fmt.Errorf("loading prociter with map replacements: %w", err) } - defer iterObjs.Close() + defer func() { + if iterObjs.DumpTask != nil { + _ = iterObjs.DumpTask.Close() + } + }() rd, err := ringbuf.NewReader(execObjs.Events) if err != nil { @@ -112,7 +117,7 @@ func Run(duration time.Duration) (*Result, error) { select { case <-stop: return - default: + case <-time.After(10 * time.Millisecond): continue } } From 7449eb61612e61ff8257e88cd7e664d4b6fd8b09 Mon Sep 17 00:00:00 2001 From: Mostafa Moradian Date: Fri, 7 Aug 2026 09:26:31 +0200 Subject: [PATCH 06/28] fix(ebpf): Restore cilium/ebpf module and rename import alias Keep github.com/cilium/ebpf as a direct go.mod require so Linux packages resolve in CI, and use the libebpf import alias requested in review. --- go.mod | 3 +-- go.sum | 15 ++++++++++++--- internal/ebpf/FEASIBILITY.md | 2 +- internal/ebpf/spike/run.go | 14 +++++++------- 4 files changed, 21 insertions(+), 13 deletions(-) diff --git a/go.mod b/go.mod index f4c2afb44..03a7cec64 100644 --- a/go.mod +++ b/go.mod @@ -7,6 +7,7 @@ require ( github.com/bits-and-blooms/bitset v1.13.0 github.com/briandowns/spinner v1.12.0 github.com/cenkalti/backoff/v4 v4.3.0 + github.com/cilium/ebpf v0.20.0 github.com/dustin/go-humanize v1.0.0 github.com/enescakir/emoji v1.0.0 github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e @@ -48,9 +49,7 @@ require ( require ( github.com/BurntSushi/toml v0.4.1 // indirect github.com/klauspost/cpuid/v2 v2.2.10 // indirect - github.com/kr/pretty v0.3.1 // indirect github.com/rivo/uniseg v0.4.2 // indirect - github.com/rogpeppe/go-internal v1.12.0 // indirect github.com/secDre4mer/pkcs7 v0.0.0-20240322103146-665324a4461d // indirect go4.org/netipx v0.0.0-20220725152314-7e7bdc8411bf // indirect golang.org/x/exp/typeparams v0.0.0-20220218215828-6cf2b201936e // indirect diff --git a/go.sum b/go.sum index 434b3bfea..89630a0a1 100644 --- a/go.sum +++ b/go.sum @@ -28,13 +28,14 @@ github.com/briandowns/spinner v1.12.0/go.mod h1:QOuQk7x+EaDASo80FEXwlwiA+j/PPIcX github.com/cenkalti/backoff/v4 v4.3.0 h1:MyRJ/UdXutAwSAT+s3wNd7MfTIcy71VQueUuFK343L8= github.com/cenkalti/backoff/v4 v4.3.0/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE= github.com/cespare/xxhash v1.1.0/go.mod h1:XrSqR1VqqWfGrhpAt58auRo0WTKS1nRRg3ghfAqPWnc= +github.com/cilium/ebpf v0.20.0 h1:atwWj9d3NffHyPZzVlx3hmw1on5CLe9eljR8VuHTwhM= +github.com/cilium/ebpf v0.20.0/go.mod h1:pzLjFymM+uZPLk/IXZUL63xdx5VXEo+enTzxkZXdycw= github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= github.com/coreos/bbolt v1.3.2/go.mod h1:iRUV2dpdMOn7Bo10OQBFzIJO9kkE559Wcmn+qkEiiKk= github.com/coreos/etcd v3.3.10+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE= github.com/coreos/go-semver v0.2.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= github.com/coreos/go-systemd v0.0.0-20190321100706-95778dfbb74e/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= github.com/coreos/pkg v0.0.0-20180928190104-399ea9e2e55f/go.mod h1:E3G3o1h8I7cfcXa63jLwjI0eiQQMgzzUDFVpN/nH/eA= -github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= @@ -58,6 +59,8 @@ github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeME github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE= github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk= +github.com/go-quicktest/qt v1.101.1-0.20240301121107-c6c8733fa1e6 h1:teYtXy9B7y5lHTp8V9KPxpYRAVA7dozigQcMiBust1s= +github.com/go-quicktest/qt v1.101.1-0.20240301121107-c6c8733fa1e6/go.mod h1:p4lGIVX+8Wa6ZPNDvqcxq36XpUDLh42FLetFU7odllI= github.com/go-sql-driver/mysql v1.5.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg= github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= @@ -104,6 +107,10 @@ github.com/jmespath/go-jmespath v0.3.0/go.mod h1:9QtRXoHjLGCJ5IBSaohpXITPlowMeeY github.com/jonboulle/clockwork v0.1.0/go.mod h1:Ii8DK3G1RaLaWxj9trq07+26W01tbo22gdxWY5EU2bo= github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY= github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y= +github.com/josharian/native v1.1.0 h1:uuaP0hAbW7Y4l0ZRQ6C9zfb7Mg1mbFKry/xzDAfmtLA= +github.com/josharian/native v1.1.0/go.mod h1:7X/raswPFr05uY3HiLlYeyQntB6OO7E/d2Cu7qoaN2w= +github.com/jsimonetti/rtnetlink/v2 v2.0.1 h1:xda7qaHDSVOsADNouv7ukSuicKZO7GgVUCXxpaIEIlM= +github.com/jsimonetti/rtnetlink/v2 v2.0.1/go.mod h1:7MoNYNbb3UaDHtF8udiJo/RH6VsTKP1pqKLUTVCvToE= github.com/jtolds/gls v4.20.0+incompatible h1:xdiiI2gbIgH/gLH7ADydsJ1uDOEzR8yvV7C0MuV77Wo= github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w= @@ -136,6 +143,10 @@ github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m github.com/mattn/go-runewidth v0.0.14 h1:+xnbZSEeDbOIg5/mE6JF0w6n9duR1l3/WmbinWVwUuU= github.com/mattn/go-runewidth v0.0.14/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= +github.com/mdlayher/netlink v1.7.2 h1:/UtM3ofJap7Vl4QWCPDGXY8d3GIY2UGSDbK+QWmY8/g= +github.com/mdlayher/netlink v1.7.2/go.mod h1:xraEF7uJbxLhc5fpHL4cPe221LI2bdttWlU+ZGLfQSw= +github.com/mdlayher/socket v0.4.1 h1:eM9y2/jlbs1M615oshPQOHZzj6R6wMT7bX5NPiQvn2U= +github.com/mdlayher/socket v0.4.1/go.mod h1:cAqeGjoufqdxWkD7DkpyS+wcefOtmu5OQ8KuoJGIReA= github.com/mitchellh/copystructure v1.0.0 h1:Laisrj+bAB6b/yJwB5Bt3ITZhGJdqmxquMKeZ+mmkFQ= github.com/mitchellh/copystructure v1.0.0/go.mod h1:SNtv71yrdKgLRyLFxmLdkAbkKEFWgYaq1OVrnRcwhnw= github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= @@ -152,7 +163,6 @@ github.com/pelletier/go-toml v1.2.0 h1:T5zMGML61Wp+FlcbWjRDT7yAxhJNAiPPLOFECq181 github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic= github.com/phayes/freeport v0.0.0-20180830031419-95f893ade6f2 h1:JhzVVoYvbOACxoUmOs6V/G4D5nPVUW73rKvXxP4XUJc= github.com/phayes/freeport v0.0.0-20180830031419-95f893ade6f2/go.mod h1:iIss55rKnNBTvrwdmkUpLnDpZoAHvWaiq5+iMmen4AE= -github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA= github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= @@ -177,7 +187,6 @@ github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJ github.com/rivo/uniseg v0.4.2 h1:YwD0ulJSJytLpiaWua0sBDusfsCZohxjxzVTYjwxfV8= github.com/rivo/uniseg v0.4.2/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88= github.com/rogpeppe/fastuuid v0.0.0-20150106093220-6724a57986af/go.mod h1:XWv6SoW27p1b0cqNHllgS5HIMJraePCO15w5zCzIWYg= -github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= github.com/saferwall/pe v1.5.6 h1:DrRLnoQFxHWJ5lJUmrH7X2L0xeUu6SUS95Dc61eW2Yc= diff --git a/internal/ebpf/FEASIBILITY.md b/internal/ebpf/FEASIBILITY.md index f9344b3ba..46aa7d58b 100644 --- a/internal/ebpf/FEASIBILITY.md +++ b/internal/ebpf/FEASIBILITY.md @@ -24,7 +24,7 @@ Explicit non-fallbacks: | Tool | Pin / note | | --- | --- | -| `github.com/cilium/ebpf` | v0.20.0 | +| `github.com/cilium/ebpf` | v0.20.0 (direct `go.mod` require; run `GOOS=linux go mod tidy` so Darwin tidy cannot drop it) | | `bpf2go` | version-matched to cilium/ebpf v0.20.0 | | clang/LLVM | Spike objects regenerated with Debian clang 19.1.7 (`golang:1.26` image) | | bpftool | Optional for inspecting BTF; not required for ordinary builds | diff --git a/internal/ebpf/spike/run.go b/internal/ebpf/spike/run.go index 6ba8aff9c..4c223b925 100644 --- a/internal/ebpf/spike/run.go +++ b/internal/ebpf/spike/run.go @@ -34,7 +34,7 @@ import ( "github.com/cilium/ebpf/link" "github.com/cilium/ebpf/ringbuf" "github.com/cilium/ebpf/rlimit" - fibebpf "github.com/rabbitstack/fibratus/internal/ebpf" + libebpf "github.com/rabbitstack/fibratus/internal/ebpf" ) const ( @@ -44,7 +44,7 @@ const ( // Result summarizes a successful spike run. type Result struct { - Prerequisites *fibebpf.PrerequisiteReport + Prerequisites *libebpf.PrerequisiteReport Snapshots int ExecEvents int Reconciled int @@ -54,7 +54,7 @@ type Result struct { // Run proves CO-RE load, shared-map replacement, race-safe startup, and // best-effort /proc enrichment on a real Linux kernel. func Run(duration time.Duration) (*Result, error) { - report, err := fibebpf.ProbePrerequisites() + report, err := libebpf.ProbePrerequisites() if err != nil { return &Result{Prerequisites: report}, fmt.Errorf("prerequisites: %w", err) } @@ -101,7 +101,7 @@ func Run(duration time.Duration) (*Result, error) { } defer rd.Close() - reconciler := fibebpf.NewStartupReconciler(4096) + reconciler := libebpf.NewStartupReconciler(4096) stop := make(chan struct{}) done := make(chan struct{}) var execCount, snapCount atomic.Uint64 @@ -125,7 +125,7 @@ func Run(duration time.Duration) (*Result, error) { if err != nil { continue } - key := fibebpf.ProcessKey{PID: ev.Tgid, StartBootTime: ev.StartBoottime} + key := libebpf.ProcessKey{PID: ev.Tgid, StartBootTime: ev.StartBoottime} comm := cString(ev.Comm[:]) filename := cString(ev.Filename[:]) switch ev.Kind { @@ -135,7 +135,7 @@ func Run(duration time.Duration) (*Result, error) { reconciler.AccountEnrichmentMiss() } snapCount.Add(1) - reconciler.UpsertSnapshot(fibebpf.ProcessRecord{ + reconciler.UpsertSnapshot(libebpf.ProcessRecord{ Key: key, Comm: comm, Filename: filename, @@ -146,7 +146,7 @@ func Run(duration time.Duration) (*Result, error) { // Short-lived execs often exit before /proc enrichment; that is expected. exe, cmdline, _ := enrichFromProc(ev.Tgid) execCount.Add(1) - _ = reconciler.EnqueueHot(fibebpf.HotEvent{ + _ = reconciler.EnqueueHot(libebpf.HotEvent{ Key: key, Kind: ev.Kind, Timestamp: ev.TimestampNs, From 53658bc02782ee8132d6e3d48fc23280cb7676ab Mon Sep 17 00:00:00 2001 From: Mostafa Moradian Date: Sat, 8 Aug 2026 12:35:12 +0200 Subject: [PATCH 07/28] refactor(bootstrap): Split bootstrap and CLI entrypoints for Linux --- cmd/fibratus/app/root.go | 25 ++-------- cmd/fibratus/app/root_linux.go | 32 +++++++++++++ cmd/fibratus/app/root_windows.go | 35 ++++++++++++++ cmd/fibratus/app/run_linux.go | 55 ++++++++++++++++++++++ cmd/fibratus/main_linux.go | 31 +++++++++++++ internal/bootstrap/bootstrap.go | 2 + internal/bootstrap/bootstrap_linux.go | 66 +++++++++++++++++++++++++++ internal/bootstrap/source.go | 2 + internal/bootstrap/source_linux.go | 49 ++++++++++++++++++++ 9 files changed, 277 insertions(+), 20 deletions(-) create mode 100644 cmd/fibratus/app/root_linux.go create mode 100644 cmd/fibratus/app/root_windows.go create mode 100644 cmd/fibratus/app/run_linux.go create mode 100644 cmd/fibratus/main_linux.go create mode 100644 internal/bootstrap/bootstrap_linux.go create mode 100644 internal/bootstrap/source_linux.go diff --git a/cmd/fibratus/app/root.go b/cmd/fibratus/app/root.go index 25f43b9ae..67145eb1d 100644 --- a/cmd/fibratus/app/root.go +++ b/cmd/fibratus/app/root.go @@ -20,15 +20,9 @@ package app import ( "errors" - "github.com/rabbitstack/fibratus/cmd/fibratus/app/capture" - "github.com/rabbitstack/fibratus/cmd/fibratus/app/config" - "github.com/rabbitstack/fibratus/cmd/fibratus/app/list" - "github.com/rabbitstack/fibratus/cmd/fibratus/app/replay" - "github.com/rabbitstack/fibratus/cmd/fibratus/app/rules" - "github.com/rabbitstack/fibratus/cmd/fibratus/app/service" - "github.com/rabbitstack/fibratus/cmd/fibratus/app/stats" - "github.com/spf13/cobra" "runtime" + + "github.com/spf13/cobra" ) // RootCmd is the entrance to Fibratus CLI @@ -44,8 +38,8 @@ var RootCmd = &cobra.Command{ `, SilenceUsage: true, PersistentPreRunE: func(cmd *cobra.Command, args []string) error { - if runtime.GOOS != "windows" { - return errors.New("fibratus can only be run on Windows operating systems") + if runtime.GOOS != "windows" && runtime.GOOS != "linux" { + return errors.New("fibratus can only be run on Windows or Linux operating systems") } if runtime.GOARCH == "386" { return errors.New("fibratus can't be run on 32-bits Windows operating systems") @@ -55,14 +49,5 @@ var RootCmd = &cobra.Command{ } func init() { - RootCmd.AddCommand(capture.Command) - RootCmd.AddCommand(replay.Command) - RootCmd.AddCommand(service.Command) - RootCmd.AddCommand(stats.Command) - RootCmd.AddCommand(config.Command) - RootCmd.AddCommand(list.Command) - RootCmd.AddCommand(rules.Command) - RootCmd.AddCommand(runCmd) - RootCmd.AddCommand(docsCmd) - RootCmd.AddCommand(versionCmd) + registerCommands() } diff --git a/cmd/fibratus/app/root_linux.go b/cmd/fibratus/app/root_linux.go new file mode 100644 index 000000000..47f828cd6 --- /dev/null +++ b/cmd/fibratus/app/root_linux.go @@ -0,0 +1,32 @@ +//go:build linux + +/* + * Copyright 2019-2020 by Nedim Sabic Sabic + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package app + +import ( + "github.com/rabbitstack/fibratus/cmd/fibratus/app/config" + "github.com/rabbitstack/fibratus/cmd/fibratus/app/list" + "github.com/rabbitstack/fibratus/cmd/fibratus/app/rules" + "github.com/rabbitstack/fibratus/cmd/fibratus/app/stats" +) + +func registerCommands() { + RootCmd.AddCommand(runCmd, rules.Command, config.Command, list.Command, stats.Command, docsCmd, versionCmd) +} diff --git a/cmd/fibratus/app/root_windows.go b/cmd/fibratus/app/root_windows.go new file mode 100644 index 000000000..f5003f624 --- /dev/null +++ b/cmd/fibratus/app/root_windows.go @@ -0,0 +1,35 @@ +//go:build windows + +/* + * Copyright 2019-2020 by Nedim Sabic Sabic + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package app + +import ( + "github.com/rabbitstack/fibratus/cmd/fibratus/app/capture" + "github.com/rabbitstack/fibratus/cmd/fibratus/app/config" + "github.com/rabbitstack/fibratus/cmd/fibratus/app/list" + "github.com/rabbitstack/fibratus/cmd/fibratus/app/replay" + "github.com/rabbitstack/fibratus/cmd/fibratus/app/rules" + "github.com/rabbitstack/fibratus/cmd/fibratus/app/service" + "github.com/rabbitstack/fibratus/cmd/fibratus/app/stats" +) + +func registerCommands() { + RootCmd.AddCommand(capture.Command, replay.Command, service.Command, stats.Command, config.Command, list.Command, rules.Command, runCmd, docsCmd, versionCmd) +} diff --git a/cmd/fibratus/app/run_linux.go b/cmd/fibratus/app/run_linux.go new file mode 100644 index 000000000..58bb7d4bc --- /dev/null +++ b/cmd/fibratus/app/run_linux.go @@ -0,0 +1,55 @@ +//go:build linux + +/* + * Copyright 2019-2020 by Nedim Sabic Sabic + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package app + +import ( + "github.com/rabbitstack/fibratus/internal/bootstrap" + "github.com/rabbitstack/fibratus/pkg/config" + ver "github.com/rabbitstack/fibratus/pkg/util/version" + "github.com/spf13/cobra" +) + +var runCmd = &cobra.Command{ + Use: "run [filter]", + Short: "Bootstrap fibratus", + Aliases: []string{"start"}, + RunE: run, +} + +var cfg = config.NewWithOpts(config.WithRun()) + +func init() { + cfg.MustViperize(runCmd) +} + +func run(_ *cobra.Command, args []string) error { + ver.Set(version) + app, err := bootstrap.NewApp(cfg, bootstrap.WithSignals()) + if err != nil { + return err + } + if err := app.Run(args); err != nil { + _ = app.Shutdown() + return err + } + app.Wait() + return app.Shutdown() +} diff --git a/cmd/fibratus/main_linux.go b/cmd/fibratus/main_linux.go new file mode 100644 index 000000000..86ff331a3 --- /dev/null +++ b/cmd/fibratus/main_linux.go @@ -0,0 +1,31 @@ +/* + * Copyright 2019-2020 by Nedim Sabic Sabic + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package main + +import ( + "os" + + "github.com/rabbitstack/fibratus/cmd/fibratus/app" +) + +func main() { + if err := app.RootCmd.Execute(); err != nil { + os.Exit(-1) + } +} diff --git a/internal/bootstrap/bootstrap.go b/internal/bootstrap/bootstrap.go index 1e5a52361..630b5f563 100644 --- a/internal/bootstrap/bootstrap.go +++ b/internal/bootstrap/bootstrap.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2021-2022 by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/internal/bootstrap/bootstrap_linux.go b/internal/bootstrap/bootstrap_linux.go new file mode 100644 index 000000000..d07148135 --- /dev/null +++ b/internal/bootstrap/bootstrap_linux.go @@ -0,0 +1,66 @@ +//go:build linux + +/* + * Copyright 2021-2022 by Nedim Sabic Sabic + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package bootstrap + +import ( + "errors" + + "github.com/rabbitstack/fibratus/pkg/config" +) + +var ErrCaptureNotWired = errors.New("linux event capture is not wired yet") + +type App struct { + config *config.Config + evs *EventSourceControl +} + +type Option func(*opts) + +type opts struct{} + +func WithSignals() Option { + return func(*opts) {} +} + +func WithDebugPrivilege() Option { + return func(*opts) {} +} + +func NewApp(cfg *config.Config, options ...Option) (*App, error) { + if err := InitConfigAndLogger(cfg); err != nil { + return nil, err + } + return &App{config: cfg, evs: NewEventSourceControl(cfg)}, nil +} + +func (f *App) Run([]string) error { + if err := f.evs.Open(f.config); err != nil { + return err + } + return ErrCaptureNotWired +} + +func (*App) Wait() {} + +func (f *App) Shutdown() error { + return f.evs.Close() +} diff --git a/internal/bootstrap/source.go b/internal/bootstrap/source.go index 683ee22f9..05931d682 100644 --- a/internal/bootstrap/source.go +++ b/internal/bootstrap/source.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2021-2022 by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/internal/bootstrap/source_linux.go b/internal/bootstrap/source_linux.go new file mode 100644 index 000000000..9c6984c83 --- /dev/null +++ b/internal/bootstrap/source_linux.go @@ -0,0 +1,49 @@ +//go:build linux + +/* + * Copyright 2021-2022 by Nedim Sabic Sabic + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package bootstrap + +import ( + "github.com/rabbitstack/fibratus/pkg/config" +) + +type EventSourceControl struct { + evs *stubEventSource +} + +func NewEventSourceControl(*config.Config) *EventSourceControl { + return &EventSourceControl{evs: &stubEventSource{}} +} + +func (s *EventSourceControl) Open(cfg *config.Config) error { + return s.evs.Open(cfg) +} + +func (s *EventSourceControl) Close() error { + return s.evs.Close() +} + +type stubEventSource struct{} + +func (*stubEventSource) Open(*config.Config) error { + return nil +} + +func (*stubEventSource) Close() error { return nil } From fa4163e573e02d6ae3e7ae6dd04ccd6525a58ad7 Mon Sep 17 00:00:00 2001 From: Mostafa Moradian Date: Sat, 8 Aug 2026 12:35:15 +0200 Subject: [PATCH 08/28] feat(event): Add Linux semantic event type identifiers --- pkg/callstack/callstack.go | 2 + pkg/callstack/callstack_linux.go | 27 ++++++++ pkg/callstack/colorize.go | 2 + pkg/cap/version/version_linux.go | 44 +++++++++++++ pkg/event/enum.go | 2 + pkg/event/enum_linux.go | 21 ++++++ pkg/event/flags.go | 2 + pkg/event/flags_linux.go | 40 ++++++++++++ pkg/event/metainfo_linux.go | 108 +++++++++++++++++++++++++++++++ pkg/event/types_linux.go | 105 ++++++++++++++++++++++++++++++ pkg/util/key/key_linux.go | 23 +++++++ 11 files changed, 376 insertions(+) create mode 100644 pkg/callstack/callstack_linux.go create mode 100644 pkg/cap/version/version_linux.go create mode 100644 pkg/event/enum_linux.go create mode 100644 pkg/event/flags_linux.go create mode 100644 pkg/event/metainfo_linux.go create mode 100644 pkg/event/types_linux.go create mode 100644 pkg/util/key/key_linux.go diff --git a/pkg/callstack/callstack.go b/pkg/callstack/callstack.go index 21f2298c1..2a0e9e63b 100644 --- a/pkg/callstack/callstack.go +++ b/pkg/callstack/callstack.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2021-present by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/pkg/callstack/callstack_linux.go b/pkg/callstack/callstack_linux.go new file mode 100644 index 000000000..b333f77f2 --- /dev/null +++ b/pkg/callstack/callstack_linux.go @@ -0,0 +1,27 @@ +//go:build linux + +/* + * Copyright 2026 by Nedim Sabic Sabic + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package callstack + +type Callstack []Frame + +type Frame struct { + PID uint32 +} diff --git a/pkg/callstack/colorize.go b/pkg/callstack/colorize.go index c49f7a1cc..f7e59c8da 100644 --- a/pkg/callstack/colorize.go +++ b/pkg/callstack/colorize.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2021-present by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/pkg/cap/version/version_linux.go b/pkg/cap/version/version_linux.go new file mode 100644 index 000000000..df2a03809 --- /dev/null +++ b/pkg/cap/version/version_linux.go @@ -0,0 +1,44 @@ +//go:build linux + +/* + * Copyright 2019-2020 by Nedim Sabic Sabic + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package version + +type Version uint16 + +const ( + EvtSecV1 Version = iota + 1 + EvtSecV2 +) + +const ( + ProcessSecV1 Version = iota + 1 + ProcessSecV2 + ProcessSecV3 + ProcessSecV4 +) + +const ( + HandleSecV1 Version = iota + 1 +) + +const ( + PESecV1 Version = iota + 1 + PESecV2 +) diff --git a/pkg/event/enum.go b/pkg/event/enum.go index e4cd47c44..326f81346 100644 --- a/pkg/event/enum.go +++ b/pkg/event/enum.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2021-2022 by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/pkg/event/enum_linux.go b/pkg/event/enum_linux.go new file mode 100644 index 000000000..ac2900f5c --- /dev/null +++ b/pkg/event/enum_linux.go @@ -0,0 +1,21 @@ +//go:build linux + +/* + * Copyright 2026 by Nedim Sabic Sabic + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package event diff --git a/pkg/event/flags.go b/pkg/event/flags.go index 693a56ba1..8cd50dd01 100644 --- a/pkg/event/flags.go +++ b/pkg/event/flags.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2021-2022 by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/pkg/event/flags_linux.go b/pkg/event/flags_linux.go new file mode 100644 index 000000000..e035ff98d --- /dev/null +++ b/pkg/event/flags_linux.go @@ -0,0 +1,40 @@ +//go:build linux + +/* + * Copyright 2026 by Nedim Sabic Sabic + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package event + +import "strings" + +type ParamFlag struct { + Name string + Value uint64 +} + +type ParamFlags []ParamFlag + +func (flags ParamFlags) String(value uint64) string { + var names []string + for _, flag := range flags { + if value&flag.Value == flag.Value { + names = append(names, flag.Name) + } + } + return strings.Join(names, "|") +} diff --git a/pkg/event/metainfo_linux.go b/pkg/event/metainfo_linux.go new file mode 100644 index 000000000..2a607787a --- /dev/null +++ b/pkg/event/metainfo_linux.go @@ -0,0 +1,108 @@ +//go:build linux + +/* + * Copyright 2026 by Nedim Sabic Sabic + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package event + +import "slices" + +type Info struct { + Name string + Category Category + Description string +} + +var events = map[Type]Info{ + CreateProcess: {Name: "CreateProcess", Category: Process, Description: "Creates a new process"}, + Execve: {Name: "Execve", Category: Process, Description: "Executes a program"}, + TerminateProcess: {Name: "TerminateProcess", Category: Process, Description: "Terminates a process"}, + Exit: {Name: "Exit", Category: Process, Description: "Exits a process"}, + ProcessRundown: {Name: "ProcessRundown", Category: Process, Description: "Reports an existing process"}, + Clone: {Name: "Clone", Category: Process, Description: "Clones a process or thread"}, +} + +var types = map[string]Type{ + "CreateProcess": CreateProcess, + "Execve": Execve, + "TerminateProcess": TerminateProcess, + "Exit": Exit, + "ProcessRundown": ProcessRundown, + "Clone": Clone, +} + +func All() []Type { + return []Type{CreateProcess, Execve, TerminateProcess, Exit, Clone} +} + +func AllWithState() []Type { + return append(All(), ProcessRundown) +} + +func MaxTypeID() uint16 { + return uint16(slices.Max(AllWithState())) +} + +func TypeToEventInfo(typ Type) Info { + if info, ok := events[typ]; ok { + return info + } + return Info{Name: "N/A", Category: Unknown} +} + +func NameToType(name string) Type { + if typ, ok := types[name]; ok { + return typ + } + return UnknownType +} + +func NameToTypes(name string) []Type { + return []Type{NameToType(name)} +} + +func GetTypesMeta() []Info { + infos := make([]Info, 0, len(events)) + for _, info := range events { + infos = append(infos, info) + } + slices.SortFunc(infos, func(a, b Info) int { + if a.Category == b.Category { + if a.Name < b.Name { + return -1 + } + if a.Name > b.Name { + return 1 + } + return 0 + } + if a.Category < b.Category { + return -1 + } + return 1 + }) + return infos +} + +func GetTypesMetaIndexed() []Info { + return GetTypesMeta() +} + +func IsKnown(name string) bool { + return NameToType(name) != UnknownType +} diff --git a/pkg/event/types_linux.go b/pkg/event/types_linux.go new file mode 100644 index 000000000..91ef4be20 --- /dev/null +++ b/pkg/event/types_linux.go @@ -0,0 +1,105 @@ +//go:build linux + +/* + * Copyright 2026 by Nedim Sabic Sabic + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package event + +import ( + "github.com/rabbitstack/fibratus/pkg/util/colorizer" + "github.com/rabbitstack/fibratus/pkg/util/hashers" +) + +type Source uint8 + +const ( + SystemLogger Source = iota + SecurityTelemetryLogger +) + +type Type uint16 + +const ( + UnknownType Type = iota + CreateProcess + Execve + TerminateProcess + Exit + ProcessRundown + Clone +) + +func (t Type) String() string { + return TypeToEventInfo(t).Name +} + +func (t Type) Category() Category { + return TypeToEventInfo(t).Category +} + +func (t Type) Subcategory() Subcategory { + return None +} + +func (t Type) Description() string { + return TypeToEventInfo(t).Description +} + +func (t Type) Hash() uint32 { + if t == UnknownType { + return 0 + } + return hashers.FnvUint32([]byte(t.String())) +} + +func (t Type) Exists() bool { + return t != UnknownType && t.String() != "N/A" +} + +func (t Type) OnlyState() bool { + return t == ProcessRundown +} + +func (t Type) CanEnrichStack() bool { + return false +} + +func (t *Type) UnmarshalYAML(unmarshal func(interface{}) error) error { + var name string + if err := unmarshal(&name); err != nil { + return err + } + *t = NameToType(name) + return nil +} + +func (t Type) ID() uint { + return uint(t) +} + +func (t Type) Source() Source { + return SystemLogger +} + +func (t Type) color() string { + return colorizer.SpanBold(colorizer.White, t.String()) +} + +func (t Type) arrow() string { + return colorizer.SpanBold(colorizer.Gray, "› ") +} diff --git a/pkg/util/key/key_linux.go b/pkg/util/key/key_linux.go new file mode 100644 index 000000000..891a85fb1 --- /dev/null +++ b/pkg/util/key/key_linux.go @@ -0,0 +1,23 @@ +//go:build linux + +/* + * Copyright 2026 by Nedim Sabic Sabic + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package key + +var RegistryValueTypes = map[uint32]string{} From 5770876674cc4dbf229cb252127a42f9e321669a Mon Sep 17 00:00:00 2001 From: Mostafa Moradian Date: Sat, 8 Aug 2026 12:35:18 +0200 Subject: [PATCH 09/28] feat(config): Add Linux event source configuration --- pkg/config/alertsender.go | 2 + pkg/config/config_linux.go | 125 +++++++++++++++++++++++++++ pkg/config/eventsource_linux.go | 101 ++++++++++++++++++++++ pkg/config/eventsource_linux_stub.go | 41 +++++++++ pkg/config/filters.go | 2 + pkg/config/filters_linux.go | 50 +++++++++++ pkg/config/output.go | 2 + pkg/config/schema_linux.go | 32 +++++++ pkg/config/transformer.go | 2 + 9 files changed, 357 insertions(+) create mode 100644 pkg/config/config_linux.go create mode 100644 pkg/config/eventsource_linux.go create mode 100644 pkg/config/eventsource_linux_stub.go create mode 100644 pkg/config/filters_linux.go create mode 100644 pkg/config/schema_linux.go diff --git a/pkg/config/alertsender.go b/pkg/config/alertsender.go index 06f033088..237b3fe97 100644 --- a/pkg/config/alertsender.go +++ b/pkg/config/alertsender.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2019-2020 by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/pkg/config/config_linux.go b/pkg/config/config_linux.go new file mode 100644 index 000000000..ecd0fd8c8 --- /dev/null +++ b/pkg/config/config_linux.go @@ -0,0 +1,125 @@ +//go:build linux + +/* + * Copyright 2026 by Nedim Sabic Sabic + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package config + +import ( + "os" + "path/filepath" + "strings" + + "github.com/rabbitstack/fibratus/pkg/util/log" + "github.com/spf13/cobra" + "github.com/spf13/pflag" + "github.com/spf13/viper" +) + +const configFile = "config-file" + +type Config struct { + EventSource EventSourceConfig `json:"eventsource" yaml:"eventsource"` + Filament FilamentConfig `json:"filament" yaml:"filament"` + API APIConfig `json:"api" yaml:"api"` + Log log.Config `json:"logging" yaml:"logging"` + Filters *Filters `json:"filters" yaml:"filters"` + ForwardMode bool `json:"forward" yaml:"forward"` + CapFile string `json:"cap.file" yaml:"cap.file"` + + flags *pflag.FlagSet + viper *viper.Viper + opts *Options +} + +type Options struct { + run bool + list bool + stats bool + validate bool +} + +type Option func(*Options) + +func WithRun() Option { return func(o *Options) { o.run = true } } +func WithList() Option { return func(o *Options) { o.list = true } } +func WithStats() Option { return func(o *Options) { o.stats = true } } +func WithValidate() Option { return func(o *Options) { o.validate = true } } + +func NewWithOpts(options ...Option) *Config { + opts := &Options{} + for _, option := range options { + option(opts) + } + v := viper.New() + v.AutomaticEnv() + v.SetEnvKeyReplacer(strings.NewReplacer("-", "_", ".", "_")) + c := &Config{ + Filters: &Filters{}, + flags: new(pflag.FlagSet), + viper: v, + opts: opts, + } + c.flags.String(configFile, filepath.Join("/etc", "fibratus", "fibratus.yml"), "Indicates the location of the configuration file") + c.flags.String(filamentName, "", "Specifies the filament to execute") + c.flags.String(filamentPath, "", "Denotes the directory where filaments are located") + c.flags.String(transport, "localhost:8080", "Specifies the underlying transport protocol for the API HTTP server") + c.flags.Bool(rulesEnabled, true, "Indicates if the rule engine is enabled and rules loaded") + c.flags.StringSlice(rulesFromPaths, nil, "Comma-separated list of rules files") + c.flags.StringSlice(macrosFromPaths, nil, "Comma-separated list of macro files") + c.flags.StringSlice(rulesFromURLs, nil, "Comma-separated list of rules URL resources") + c.flags.Bool(matchAll, true, "Indicates if the match all strategy is enabled") + c.EventSource.AddFlags(c.flags) + c.Log.AddFlags(c.flags) + return c +} + +func (c *Config) MustViperize(cmd *cobra.Command) { + cmd.PersistentFlags().AddFlagSet(c.flags) + if err := c.viper.BindPFlags(cmd.PersistentFlags()); err != nil { + panic(err) + } +} + +func (c *Config) Init() error { + c.EventSource.initFromViper(c.viper) + c.Filament.initFromViper(c.viper) + c.API.initFromViper(c.viper) + c.Log.InitFromViper(c.viper) + c.Filters.initFromViper(c.viper) + c.ForwardMode = c.viper.GetBool("forward") + c.CapFile = c.viper.GetString("cap.file") + return nil +} + +func (c *Config) GetConfigFile() string { return c.viper.GetString(configFile) } +func (c *Config) File() string { return c.GetConfigFile() } +func (c *Config) GetFilters() []*FilterConfig { + if c.Filters == nil { + return nil + } + return c.Filters.filters +} +func (c *Config) TryLoadFile(file string) error { + c.viper.SetConfigFile(file) + return c.viper.ReadInConfig() +} +func (c *Config) Validate() error { return nil } +func (c *Config) IsCaptureSet() bool { return c.CapFile != "" } +func (c *Config) IsFilamentSet() bool { return c.Filament.Name != "" } +func (c *Config) ConfigExists() bool { _, err := os.Stat(c.File()); return err == nil } diff --git a/pkg/config/eventsource_linux.go b/pkg/config/eventsource_linux.go new file mode 100644 index 000000000..077ad62f7 --- /dev/null +++ b/pkg/config/eventsource_linux.go @@ -0,0 +1,101 @@ +//go:build linux && eventsource + +/* + * Copyright 2026 by Nedim Sabic Sabic + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package config + +import ( + "github.com/rabbitstack/fibratus/pkg/event" + pstypes "github.com/rabbitstack/fibratus/pkg/ps/types" + "github.com/rabbitstack/fibratus/pkg/util/bitmask" + "github.com/spf13/pflag" + "github.com/spf13/viper" +) + +const ( + enableProcessEvents = "eventsource.enable-process" + enableFileEvents = "eventsource.enable-file" + enableNetEvents = "eventsource.enable-net" + enableMemEvents = "eventsource.enable-mem" + excludedEvents = "eventsource.blacklist.events" + excludedImages = "eventsource.blacklist.images" +) + +type EventSourceConfig struct { + EnableProcessEvents bool `json:"enable-process" yaml:"enable-process"` + EnableFileIOEvents bool `json:"enable-file" yaml:"enable-file"` + EnableNetEvents bool `json:"enable-net" yaml:"enable-net"` + EnableMemEvents bool `json:"enable-mem" yaml:"enable-mem"` + ExcludedEvents []string `json:"blacklist.events" yaml:"blacklist.events"` + ExcludedImages []string `json:"blacklist.images" yaml:"blacklist.images"` + + dropMasks *bitmask.Bitmask + allMasks *bitmask.Bitmask + excludedImages map[string]bool +} + +func (c *EventSourceConfig) AddFlags(flags *pflag.FlagSet) { + flags.Bool(enableProcessEvents, true, "Determines whether process events are collected") + flags.Bool(enableFileEvents, true, "Determines whether file events are collected") + flags.Bool(enableNetEvents, true, "Determines whether network events are collected") + flags.Bool(enableMemEvents, true, "Determines whether memory events are collected") + flags.StringSlice(excludedEvents, nil, "A list of event names to drop") + flags.StringSlice(excludedImages, nil, "A list of image names to drop") +} + +func (c *EventSourceConfig) initFromViper(v *viper.Viper) { + c.EnableProcessEvents = v.GetBool(enableProcessEvents) + c.EnableFileIOEvents = v.GetBool(enableFileEvents) + c.EnableNetEvents = v.GetBool(enableNetEvents) + c.EnableMemEvents = v.GetBool(enableMemEvents) + c.ExcludedEvents = v.GetStringSlice(excludedEvents) + c.ExcludedImages = v.GetStringSlice(excludedImages) + c.Init() +} + +func (c *EventSourceConfig) Init() { + c.dropMasks = bitmask.New() + c.allMasks = bitmask.New() + c.excludedImages = make(map[string]bool) + for _, name := range c.ExcludedEvents { + for _, typ := range event.NameToTypes(name) { + c.dropMasks.Set(typ.ID()) + } + } + for _, typ := range event.AllWithState() { + c.allMasks.Set(typ.ID()) + } + for _, name := range c.ExcludedImages { + c.excludedImages[name] = true + } +} + +func (c *EventSourceConfig) SetDropMask(typ event.Type) { c.dropMasks.Set(typ.ID()) } +func (c *EventSourceConfig) TestDropMask(typ event.Type) bool { + return c.dropMasks != nil && c.dropMasks.IsSet(typ.ID()) +} +func (c *EventSourceConfig) ExcludeEvent(id uint) bool { + return c.dropMasks != nil && c.dropMasks.IsSet(id) +} +func (c *EventSourceConfig) EventExists(id uint) bool { + return c.allMasks != nil && c.allMasks.IsSet(id) +} +func (c *EventSourceConfig) ExcludeImage(ps *pstypes.PS) bool { + return ps != nil && c.excludedImages[ps.Name] +} diff --git a/pkg/config/eventsource_linux_stub.go b/pkg/config/eventsource_linux_stub.go new file mode 100644 index 000000000..1b61dfc0a --- /dev/null +++ b/pkg/config/eventsource_linux_stub.go @@ -0,0 +1,41 @@ +//go:build linux && !eventsource + +/* + * Copyright 2026 by Nedim Sabic Sabic + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package config + +import ( + "github.com/spf13/pflag" + "github.com/spf13/viper" +) + +type EventSourceConfig struct { + EnableProcessEvents bool + EnableFileIOEvents bool + EnableNetEvents bool + EnableMemEvents bool +} + +func (c *EventSourceConfig) AddFlags(flags *pflag.FlagSet) { + flags.Bool("eventsource.enable-process", true, "Determines whether process events are collected") +} + +func (c *EventSourceConfig) initFromViper(v *viper.Viper) { + c.EnableProcessEvents = v.GetBool("eventsource.enable-process") +} diff --git a/pkg/config/filters.go b/pkg/config/filters.go index 3d0bdfe5e..6d0ad448e 100644 --- a/pkg/config/filters.go +++ b/pkg/config/filters.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2020-2021 by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/pkg/config/filters_linux.go b/pkg/config/filters_linux.go new file mode 100644 index 000000000..3791cfdb7 --- /dev/null +++ b/pkg/config/filters_linux.go @@ -0,0 +1,50 @@ +//go:build linux + +/* + * Copyright 2026 by Nedim Sabic Sabic + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package config + +import "github.com/spf13/viper" + +const ( + rulesEnabled = "filters.rules.enabled" + rulesFromPaths = "filters.rules.from-paths" + rulesFromURLs = "filters.rules.from-urls" + macrosFromPaths = "filters.macros.from-paths" + matchAll = "filters.match-all" +) + +type FilterConfig struct{} + +type Filters struct { + Rules struct { + Enabled bool + FromPaths []string + FromURLs []string + } + MatchAll bool + filters []*FilterConfig +} + +func (f *Filters) initFromViper(v *viper.Viper) { + f.Rules.Enabled = v.GetBool(rulesEnabled) + f.Rules.FromPaths = v.GetStringSlice(rulesFromPaths) + f.Rules.FromURLs = v.GetStringSlice(rulesFromURLs) + f.MatchAll = v.GetBool(matchAll) +} diff --git a/pkg/config/output.go b/pkg/config/output.go index 478ac4b2b..d3a88fe91 100644 --- a/pkg/config/output.go +++ b/pkg/config/output.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2019-2020 by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/pkg/config/schema_linux.go b/pkg/config/schema_linux.go new file mode 100644 index 000000000..6329e0a8b --- /dev/null +++ b/pkg/config/schema_linux.go @@ -0,0 +1,32 @@ +//go:build linux + +/* + * Copyright 2026 by Nedim Sabic Sabic + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package config + +import _ "embed" + +//go:embed config.schema.json +var configSchema string + +//go:embed rules.schema.json +var rulesSchema string + +//go:embed macros.schema.json +var macrosSchema string diff --git a/pkg/config/transformer.go b/pkg/config/transformer.go index 24b5df7d6..c2d6fb331 100644 --- a/pkg/config/transformer.go +++ b/pkg/config/transformer.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2019-2020 by Nedim Sabic Sabic * https://www.fibratus.io From 09ffee5501c8fdc458ae45286eb69dd6edf2447a Mon Sep 17 00:00:00 2001 From: Mostafa Moradian Date: Sat, 8 Aug 2026 12:35:25 +0200 Subject: [PATCH 10/28] refactor(ps): Introduce Resolver and Linux snapshotter --- pkg/ps/resolver.go | 25 +++++++ pkg/ps/types/types_linux.go | 127 ++++++++++++++++++++++++++++++++++++ 2 files changed, 152 insertions(+) create mode 100644 pkg/ps/resolver.go create mode 100644 pkg/ps/types/types_linux.go diff --git a/pkg/ps/resolver.go b/pkg/ps/resolver.go new file mode 100644 index 000000000..67414c3d8 --- /dev/null +++ b/pkg/ps/resolver.go @@ -0,0 +1,25 @@ +/* + * Copyright 2026 by Nedim Sabic Sabic + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ps + +import pstypes "github.com/rabbitstack/fibratus/pkg/ps/types" + +type Resolver interface { + Find(pid uint32) (bool, *pstypes.PS) +} diff --git a/pkg/ps/types/types_linux.go b/pkg/ps/types/types_linux.go new file mode 100644 index 000000000..138ef02f8 --- /dev/null +++ b/pkg/ps/types/types_linux.go @@ -0,0 +1,127 @@ +//go:build linux + +/* + * Copyright 2026 by Nedim Sabic Sabic + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package types + +import ( + "fmt" + "strings" + "sync" + "time" + + "github.com/rabbitstack/fibratus/pkg/util/va" +) + +type PS struct { + sync.RWMutex + PID uint32 `json:"pid"` + Ppid uint32 `json:"ppid"` + Name string `json:"name"` + Cmdline string `json:"comm"` + Exe string `json:"exe"` + Cwd string `json:"cwd"` + Args []string `json:"args"` + StartTime time.Time `json:"started"` + StartBootTime uint64 `json:"start_boot_time"` + UID uint32 `json:"uid"` + GID uint32 `json:"gid"` + Username string `json:"username"` + Envs map[string]string `json:"envs"` + Parent *PS `json:"parent"` + Threads map[uint32]Thread `json:"-"` + Mmaps []Mmap `json:"mmaps"` + Modules []Module `json:"modules"` +} + +func (ps *PS) String() string { + return fmt.Sprintf("Pid: %d\nPpid: %d\nName: %s\nCmdline: %s\nExe: %s", ps.PID, ps.Ppid, ps.Name, ps.Cmdline, ps.Exe) +} + +func (ps *PS) StringShort() string { + return ps.String() +} + +func (ps *PS) Ancestors() []string { + var ancestors []string + Walk(func(parent *PS) { + ancestors = append(ancestors, fmt.Sprintf("%s (%d)", parent.Name, parent.PID)) + }, ps) + return ancestors +} + +type Thread struct { + Tid uint32 + Pid uint32 +} + +type Module struct { + Name string + BaseAddress va.Address + Size uint64 +} + +type Mmap struct { + BaseAddress va.Address + Size uint64 + Protection uint32 + Type string + File string +} + +func (m *Mmap) ProtectMask() string { + return "" +} + +func (ps *PS) AddThread(thread Thread) { + if ps.Threads == nil { + ps.Threads = make(map[uint32]Thread) + } + ps.Threads[thread.Tid] = thread +} + +func (ps *PS) RemoveThread(tid uint32) { + delete(ps.Threads, tid) +} + +func (ps *PS) AddMmap(mmap Mmap) { + ps.Mmaps = append(ps.Mmaps, mmap) +} + +func (ps *PS) RemoveMmap(addr va.Address) { + for i, mmap := range ps.Mmaps { + if mmap.BaseAddress == addr { + ps.Mmaps = append(ps.Mmaps[:i], ps.Mmaps[i+1:]...) + return + } + } +} + +func (ps *PS) FindMmap(addr va.Address) *Mmap { + for i := range ps.Mmaps { + if ps.Mmaps[i].BaseAddress == addr { + return &ps.Mmaps[i] + } + } + return nil +} + +func (ps *PS) IsSvchost() bool { + return strings.EqualFold(ps.Name, "svchost.exe") +} From 2bb9455cdb79182360c9b66eeaf683f94c95620f Mon Sep 17 00:00:00 2001 From: Mostafa Moradian Date: Sat, 8 Aug 2026 12:35:27 +0200 Subject: [PATCH 11/28] fix(build): Gate remaining Windows-only packages for Linux builds --- cmd/fibratus/app/config/config.go | 2 + cmd/fibratus/app/config/config_linux.go | 25 +++++++++++++ cmd/fibratus/app/list/list.go | 2 + cmd/fibratus/app/list/list_linux.go | 25 +++++++++++++ cmd/fibratus/app/rules/create.go | 2 + cmd/fibratus/app/rules/list.go | 2 + cmd/fibratus/app/rules/rules.go | 2 + cmd/fibratus/app/rules/rules_linux.go | 25 +++++++++++++ cmd/fibratus/app/rules/validate.go | 2 + cmd/fibratus/app/stats/stats.go | 2 + cmd/fibratus/app/stats/stats_linux.go | 25 +++++++++++++ internal/evasion/config.go | 2 + internal/evasion/direct_syscall.go | 2 + internal/evasion/indirect_syscall.go | 2 + internal/evasion/scanner.go | 2 + pkg/filter/ql/functions/get_reg_value.go | 2 + .../ql/functions/get_reg_value_linux.go | 29 +++++++++++++++ pkg/util/log/logger.go | 2 + pkg/util/log/logger_linux.go | 37 +++++++++++++++++++ pkg/util/va/region.go | 2 + pkg/util/va/ws.go | 2 + 21 files changed, 196 insertions(+) create mode 100644 cmd/fibratus/app/config/config_linux.go create mode 100644 cmd/fibratus/app/list/list_linux.go create mode 100644 cmd/fibratus/app/rules/rules_linux.go create mode 100644 cmd/fibratus/app/stats/stats_linux.go create mode 100644 pkg/filter/ql/functions/get_reg_value_linux.go create mode 100644 pkg/util/log/logger_linux.go diff --git a/cmd/fibratus/app/config/config.go b/cmd/fibratus/app/config/config.go index 88810d92b..62679dd8a 100644 --- a/cmd/fibratus/app/config/config.go +++ b/cmd/fibratus/app/config/config.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2019-2020 by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/cmd/fibratus/app/config/config_linux.go b/cmd/fibratus/app/config/config_linux.go new file mode 100644 index 000000000..01ea46121 --- /dev/null +++ b/cmd/fibratus/app/config/config_linux.go @@ -0,0 +1,25 @@ +//go:build linux + +/* + * Copyright 2026 by Nedim Sabic Sabic + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package config + +import "github.com/spf13/cobra" + +var Command = &cobra.Command{Use: "config", Short: "Show runtime config"} diff --git a/cmd/fibratus/app/list/list.go b/cmd/fibratus/app/list/list.go index 92ab1eff6..961e4e107 100644 --- a/cmd/fibratus/app/list/list.go +++ b/cmd/fibratus/app/list/list.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2019-2020 by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/cmd/fibratus/app/list/list_linux.go b/cmd/fibratus/app/list/list_linux.go new file mode 100644 index 000000000..c2c68dcfc --- /dev/null +++ b/cmd/fibratus/app/list/list_linux.go @@ -0,0 +1,25 @@ +//go:build linux + +/* + * Copyright 2026 by Nedim Sabic Sabic + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package list + +import "github.com/spf13/cobra" + +var Command = &cobra.Command{Use: "list", Short: "Show available Linux runtime information"} diff --git a/cmd/fibratus/app/rules/create.go b/cmd/fibratus/app/rules/create.go index c21dc3bbc..12f55f6cb 100644 --- a/cmd/fibratus/app/rules/create.go +++ b/cmd/fibratus/app/rules/create.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2021-2022 by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/cmd/fibratus/app/rules/list.go b/cmd/fibratus/app/rules/list.go index 666af4f6d..525dd0217 100644 --- a/cmd/fibratus/app/rules/list.go +++ b/cmd/fibratus/app/rules/list.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2021-2022 by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/cmd/fibratus/app/rules/rules.go b/cmd/fibratus/app/rules/rules.go index d925aa557..ca387bfdb 100644 --- a/cmd/fibratus/app/rules/rules.go +++ b/cmd/fibratus/app/rules/rules.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2021-2022 by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/cmd/fibratus/app/rules/rules_linux.go b/cmd/fibratus/app/rules/rules_linux.go new file mode 100644 index 000000000..42ed7d2aa --- /dev/null +++ b/cmd/fibratus/app/rules/rules_linux.go @@ -0,0 +1,25 @@ +//go:build linux + +/* + * Copyright 2026 by Nedim Sabic Sabic + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package rules + +import "github.com/spf13/cobra" + +var Command = &cobra.Command{Use: "rules", Short: "Manage detection rules"} diff --git a/cmd/fibratus/app/rules/validate.go b/cmd/fibratus/app/rules/validate.go index 9ab621d04..56b2b227f 100644 --- a/cmd/fibratus/app/rules/validate.go +++ b/cmd/fibratus/app/rules/validate.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2021-2022 by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/cmd/fibratus/app/stats/stats.go b/cmd/fibratus/app/stats/stats.go index 929775409..b8d5c5e25 100644 --- a/cmd/fibratus/app/stats/stats.go +++ b/cmd/fibratus/app/stats/stats.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2019-2020 by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/cmd/fibratus/app/stats/stats_linux.go b/cmd/fibratus/app/stats/stats_linux.go new file mode 100644 index 000000000..3a5825847 --- /dev/null +++ b/cmd/fibratus/app/stats/stats_linux.go @@ -0,0 +1,25 @@ +//go:build linux + +/* + * Copyright 2026 by Nedim Sabic Sabic + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package stats + +import "github.com/spf13/cobra" + +var Command = &cobra.Command{Use: "stats", Short: "Show runtime statistics"} diff --git a/internal/evasion/config.go b/internal/evasion/config.go index 8832553f1..531fe4934 100644 --- a/internal/evasion/config.go +++ b/internal/evasion/config.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2021-present by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/internal/evasion/direct_syscall.go b/internal/evasion/direct_syscall.go index e7ef61a9c..6407389a3 100644 --- a/internal/evasion/direct_syscall.go +++ b/internal/evasion/direct_syscall.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2021-present by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/internal/evasion/indirect_syscall.go b/internal/evasion/indirect_syscall.go index a339b7e45..8a703ab0d 100644 --- a/internal/evasion/indirect_syscall.go +++ b/internal/evasion/indirect_syscall.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2021-present by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/internal/evasion/scanner.go b/internal/evasion/scanner.go index 26951f0fd..43babe8b5 100644 --- a/internal/evasion/scanner.go +++ b/internal/evasion/scanner.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2021-present by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/pkg/filter/ql/functions/get_reg_value.go b/pkg/filter/ql/functions/get_reg_value.go index ecdd934f8..8a67fed9b 100644 --- a/pkg/filter/ql/functions/get_reg_value.go +++ b/pkg/filter/ql/functions/get_reg_value.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2021-2022 by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/pkg/filter/ql/functions/get_reg_value_linux.go b/pkg/filter/ql/functions/get_reg_value_linux.go new file mode 100644 index 000000000..926363826 --- /dev/null +++ b/pkg/filter/ql/functions/get_reg_value_linux.go @@ -0,0 +1,29 @@ +//go:build linux + +/* + * Copyright 2026 by Nedim Sabic Sabic + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package functions + +type GetRegValue struct{} + +func (GetRegValue) Call([]interface{}) (interface{}, bool) { return nil, false } +func (GetRegValue) Desc() FunctionDesc { + return FunctionDesc{Name: GetRegValueFn} +} +func (GetRegValue) Name() Fn { return GetRegValueFn } diff --git a/pkg/util/log/logger.go b/pkg/util/log/logger.go index e02e6989e..452b15940 100644 --- a/pkg/util/log/logger.go +++ b/pkg/util/log/logger.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2019-2020 by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/pkg/util/log/logger_linux.go b/pkg/util/log/logger_linux.go new file mode 100644 index 000000000..cd20c902c --- /dev/null +++ b/pkg/util/log/logger_linux.go @@ -0,0 +1,37 @@ +//go:build linux + +/* + * Copyright 2026 by Nedim Sabic Sabic + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package log + +import "github.com/sirupsen/logrus" + +func InitFromConfig(c Config, _ string) error { + level, err := logrus.ParseLevel(c.Level) + if err != nil { + return err + } + logrus.SetLevel(level) + if c.Formatter == "json" { + logrus.SetFormatter(&logrus.JSONFormatter{}) + } else { + logrus.SetFormatter(&logrus.TextFormatter{DisableQuote: true}) + } + return nil +} diff --git a/pkg/util/va/region.go b/pkg/util/va/region.go index 648f10b45..5d6f268d7 100644 --- a/pkg/util/va/region.go +++ b/pkg/util/va/region.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2021-2022 by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/pkg/util/va/ws.go b/pkg/util/va/ws.go index f2a06c167..397b7b0ee 100644 --- a/pkg/util/va/ws.go +++ b/pkg/util/va/ws.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2021-present by Nedim Sabic Sabic * https://www.fibratus.io From 6cf6d3bb1138fea63f194e924f6f7b6feffe6b38 Mon Sep 17 00:00:00 2001 From: Mostafa Moradian Date: Sat, 8 Aug 2026 20:46:06 +0200 Subject: [PATCH 12/28] fix(build): Gate Windows-only packages for Linux compilation Move shared catalogs out of GOOS-auto-gated filenames, tag remaining Windows packages and tests, and split colorizer/ntstatus so Linux builds no longer pull golang.org/x/sys/windows. --- pkg/aggregator/aggregator.go | 2 - pkg/aggregator/imports_windows.go | 27 + pkg/alertsender/eventlog/config.go | 2 + pkg/alertsender/eventlog/eventlog.go | 2 + pkg/alertsender/eventlog/eventlog_test.go | 2 + pkg/alertsender/systray/config.go | 2 + pkg/alertsender/systray/systray.go | 2 + pkg/alertsender/systray/systray_test.go | 2 + pkg/config/eventsource_linux.go | 2 +- pkg/config/filters.go | 2 - pkg/config/filters_linux.go | 50 - pkg/config/output_test.go | 2 + pkg/config/print_test.go | 2 + pkg/config/transformer_test.go | 2 + pkg/event/batch_test.go | 2 + pkg/event/bitset_test.go | 2 + pkg/event/flags_test.go | 2 + pkg/event/formatter_test.go | 2 + pkg/event/marshaller_test.go | 2 + pkg/event/params/names.go | 302 ++++ pkg/event/params/param_types.go | 142 ++ pkg/event/queue_test.go | 2 + pkg/event/stackwalk.go | 2 + pkg/event/stackwalk_test.go | 2 + pkg/filter/fields/defs.go | 1304 +++++++++++++++++ pkg/filter/filter_test.go | 2 + pkg/filter/ql/functions/get_reg_value_test.go | 2 + pkg/filter/ql/functions/minidump.go | 2 + pkg/fs/file_class.go | 2 + pkg/outputs/eventlog/api.go | 2 + pkg/outputs/eventlog/config.go | 2 + pkg/outputs/eventlog/eventlog.go | 2 + pkg/outputs/eventlog/eventlog_test.go | 2 + pkg/pe/header.go | 2 + pkg/pe/header_test.go | 2 + pkg/pe/parser.go | 2 + pkg/pe/parser_test.go | 2 + pkg/rules/compiler_test.go | 2 + pkg/rules/engine_test.go | 2 + pkg/rules/sequence_test.go | 2 + pkg/sys/dbghelp.go | 2 + pkg/sys/device.go | 2 + pkg/sys/device_test.go | 2 + pkg/sys/doc.go | 2 + pkg/sys/fs.go | 2 + pkg/sys/handle.go | 2 + pkg/sys/mem.go | 2 + pkg/sys/object.go | 2 + pkg/sys/privilege.go | 2 + pkg/sys/process.go | 2 + pkg/sys/process_test.go | 2 + pkg/sys/rid.go | 2 + pkg/sys/shell.go | 2 + pkg/sys/syscall.go | 2 + pkg/sys/trust.go | 2 + pkg/sys/trust_test.go | 2 + pkg/sys/util.go | 2 + pkg/sys/window.go | 2 + pkg/sys/wts.go | 2 + pkg/sys/zsyscall_windows.go | 2 + pkg/util/colorizer/colorizer.go | 19 - pkg/util/colorizer/colorizer_stub.go | 23 + pkg/util/colorizer/colorizer_windows.go | 44 + pkg/util/eventlog/eventid.go | 2 + pkg/util/eventlog/eventid_test.go | 2 + pkg/util/eventlog/eventlog.go | 2 + .../ntstatus/status_linux.go} | 30 +- .../ntstatus/{status.go => status_windows.go} | 2 + 68 files changed, 1967 insertions(+), 92 deletions(-) create mode 100644 pkg/aggregator/imports_windows.go delete mode 100644 pkg/config/filters_linux.go create mode 100644 pkg/event/params/names.go create mode 100644 pkg/event/params/param_types.go create mode 100644 pkg/filter/fields/defs.go create mode 100644 pkg/util/colorizer/colorizer_stub.go create mode 100644 pkg/util/colorizer/colorizer_windows.go rename pkg/{config/eventsource_linux_stub.go => util/ntstatus/status_linux.go} (55%) rename pkg/util/ntstatus/{status.go => status_windows.go} (99%) diff --git a/pkg/aggregator/aggregator.go b/pkg/aggregator/aggregator.go index 5993bba0c..d389119b4 100644 --- a/pkg/aggregator/aggregator.go +++ b/pkg/aggregator/aggregator.go @@ -33,14 +33,12 @@ import ( _ "github.com/rabbitstack/fibratus/pkg/outputs/amqp" _ "github.com/rabbitstack/fibratus/pkg/outputs/console" _ "github.com/rabbitstack/fibratus/pkg/outputs/elasticsearch" - _ "github.com/rabbitstack/fibratus/pkg/outputs/eventlog" _ "github.com/rabbitstack/fibratus/pkg/outputs/http" _ "github.com/rabbitstack/fibratus/pkg/outputs/null" // initialize alert senders _ "github.com/rabbitstack/fibratus/pkg/alertsender/mail" _ "github.com/rabbitstack/fibratus/pkg/alertsender/slack" - _ "github.com/rabbitstack/fibratus/pkg/alertsender/systray" // initialize transformers _ "github.com/rabbitstack/fibratus/pkg/aggregator/transformers/remove" diff --git a/pkg/aggregator/imports_windows.go b/pkg/aggregator/imports_windows.go new file mode 100644 index 000000000..e65eed8a7 --- /dev/null +++ b/pkg/aggregator/imports_windows.go @@ -0,0 +1,27 @@ +//go:build windows + +/* + * Copyright 2019-2020 by Nedim Sabic Sabic + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package aggregator + +import ( + // initialize Windows-only outputs and alert senders + _ "github.com/rabbitstack/fibratus/pkg/alertsender/systray" + _ "github.com/rabbitstack/fibratus/pkg/outputs/eventlog" +) diff --git a/pkg/alertsender/eventlog/config.go b/pkg/alertsender/eventlog/config.go index d93d398d9..9960c11a5 100644 --- a/pkg/alertsender/eventlog/config.go +++ b/pkg/alertsender/eventlog/config.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2019-2024 by Nedim Sabic Sabic and Contributors * https://www.fibratus.io diff --git a/pkg/alertsender/eventlog/eventlog.go b/pkg/alertsender/eventlog/eventlog.go index c6e111d45..837aa8d8e 100644 --- a/pkg/alertsender/eventlog/eventlog.go +++ b/pkg/alertsender/eventlog/eventlog.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2019-2024 by Nedim Sabic Sabic and Contributors * https://www.fibratus.io diff --git a/pkg/alertsender/eventlog/eventlog_test.go b/pkg/alertsender/eventlog/eventlog_test.go index 0d9ae3891..3b98d49bc 100644 --- a/pkg/alertsender/eventlog/eventlog_test.go +++ b/pkg/alertsender/eventlog/eventlog_test.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2019-2024 by Nedim Sabic Sabic and Contributors * https://www.fibratus.io diff --git a/pkg/alertsender/systray/config.go b/pkg/alertsender/systray/config.go index a1c5d237c..5298f66f0 100644 --- a/pkg/alertsender/systray/config.go +++ b/pkg/alertsender/systray/config.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2021-2022 by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/pkg/alertsender/systray/systray.go b/pkg/alertsender/systray/systray.go index f0353ba7d..00bd2e4c1 100644 --- a/pkg/alertsender/systray/systray.go +++ b/pkg/alertsender/systray/systray.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2021-2022 by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/pkg/alertsender/systray/systray_test.go b/pkg/alertsender/systray/systray_test.go index 2d49821a4..47d55b63b 100644 --- a/pkg/alertsender/systray/systray_test.go +++ b/pkg/alertsender/systray/systray_test.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2021-2022 by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/pkg/config/eventsource_linux.go b/pkg/config/eventsource_linux.go index 077ad62f7..43e7476bd 100644 --- a/pkg/config/eventsource_linux.go +++ b/pkg/config/eventsource_linux.go @@ -1,4 +1,4 @@ -//go:build linux && eventsource +//go:build linux /* * Copyright 2026 by Nedim Sabic Sabic diff --git a/pkg/config/filters.go b/pkg/config/filters.go index 6d0ad448e..3d0bdfe5e 100644 --- a/pkg/config/filters.go +++ b/pkg/config/filters.go @@ -1,5 +1,3 @@ -//go:build windows - /* * Copyright 2020-2021 by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/pkg/config/filters_linux.go b/pkg/config/filters_linux.go deleted file mode 100644 index 3791cfdb7..000000000 --- a/pkg/config/filters_linux.go +++ /dev/null @@ -1,50 +0,0 @@ -//go:build linux - -/* - * Copyright 2026 by Nedim Sabic Sabic - * https://www.fibratus.io - * All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package config - -import "github.com/spf13/viper" - -const ( - rulesEnabled = "filters.rules.enabled" - rulesFromPaths = "filters.rules.from-paths" - rulesFromURLs = "filters.rules.from-urls" - macrosFromPaths = "filters.macros.from-paths" - matchAll = "filters.match-all" -) - -type FilterConfig struct{} - -type Filters struct { - Rules struct { - Enabled bool - FromPaths []string - FromURLs []string - } - MatchAll bool - filters []*FilterConfig -} - -func (f *Filters) initFromViper(v *viper.Viper) { - f.Rules.Enabled = v.GetBool(rulesEnabled) - f.Rules.FromPaths = v.GetStringSlice(rulesFromPaths) - f.Rules.FromURLs = v.GetStringSlice(rulesFromURLs) - f.MatchAll = v.GetBool(matchAll) -} diff --git a/pkg/config/output_test.go b/pkg/config/output_test.go index 338786a71..7aa60a487 100644 --- a/pkg/config/output_test.go +++ b/pkg/config/output_test.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2019-2020 by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/pkg/config/print_test.go b/pkg/config/print_test.go index e5cf70478..036226c86 100644 --- a/pkg/config/print_test.go +++ b/pkg/config/print_test.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2019-2020 by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/pkg/config/transformer_test.go b/pkg/config/transformer_test.go index 9000fd3d0..eaed5b497 100644 --- a/pkg/config/transformer_test.go +++ b/pkg/config/transformer_test.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2019-2020 by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/pkg/event/batch_test.go b/pkg/event/batch_test.go index e53039d1b..0d2fe6826 100644 --- a/pkg/event/batch_test.go +++ b/pkg/event/batch_test.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2019-2020 by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/pkg/event/bitset_test.go b/pkg/event/bitset_test.go index df69110db..84903ac5c 100644 --- a/pkg/event/bitset_test.go +++ b/pkg/event/bitset_test.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2021-2022 by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/pkg/event/flags_test.go b/pkg/event/flags_test.go index 48e6351dd..4ce531ea7 100644 --- a/pkg/event/flags_test.go +++ b/pkg/event/flags_test.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2021-2022 by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/pkg/event/formatter_test.go b/pkg/event/formatter_test.go index 044a4c128..f5f534664 100644 --- a/pkg/event/formatter_test.go +++ b/pkg/event/formatter_test.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2019-2020 by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/pkg/event/marshaller_test.go b/pkg/event/marshaller_test.go index 37be2a3e6..81d2426ee 100644 --- a/pkg/event/marshaller_test.go +++ b/pkg/event/marshaller_test.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2019-2020 by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/pkg/event/params/names.go b/pkg/event/params/names.go new file mode 100644 index 000000000..cb269f02c --- /dev/null +++ b/pkg/event/params/names.go @@ -0,0 +1,302 @@ +/* + * Copyright 2019-2020 by Nedim Sabic Sabic + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package params + +const ( + // NTStatus is the parameter that identifies the NTSTATUS value. + NTStatus = "status" + + // ProcessID represents the process identifier. + ProcessID = "pid" + // TargetProcessID represents the target process identifier. + TargetProcessID = "target_pid" + // ProcessObject field represents the address of the process object in the kernel. + ProcessObject = "kproc" + // ThreadID field represents the thread identifier. + ThreadID = "tid" + // Callstack field represents the thread callstack. + Callstack = "callstack" + // CallstackTimestamp field identifvies the callstack timestamp parameter. + CallstackTimestamp = "callstack_timestamp" + // ProcessParentID field represents the parent process identifier. + ProcessParentID = "ppid" + // ProcessRealParentID field presents the real parent process identifier. + ProcessRealParentID = "real_ppid" + // SessionID fields represents the session identifier. + SessionID = "session_id" + // UserSID field is the security identifier associated to the process token under which it is run. + UserSID = "sid" + // Username field represents the username under which the event was generated. + Username = "username" + // Domain field represents the domain under which the event was generated. + Domain = "domain" + // ProcessName field denotes the process Module name. + ProcessName = "name" + // Exe field denotes the full path of the executable. + Exe = "exe" + // Cmdline field represents the process command line. + Cmdline = "cmdline" + // DTB field denotes the address of the process directory table. + DTB = "directory_table_base" + // ProcessFlags field denotes the process creation flags + ProcessFlags = "flags" + // ExitStatus is the field that represents the process exit status. + ExitStatus = "exit_status" + // StartTime field denotes the process start time. + StartTime = "start_time" + // ProcessTokenIntegrityLevel field denotes the process integrity level. + ProcessTokenIntegrityLevel = "token_integrity_level" + // ProcessTokenElevationType field designates the process token elevation type. + ProcessTokenElevationType = "token_elevation_type" + // ProcessTokenIsElevated field designates if the process token is elevated. + ProcessTokenIsElevated = "token_is_elevated" + + // DesiredAccess field denotes the access rights for different kernel objects such as processes or threads. + DesiredAccess = "desired_access" + + // BasePrio field is the thread base priority assigned by the scheduler. + BasePrio = "base_prio" + // IOPrio represents the filed that indicates the thread I/O priority. + IOPrio = "io_prio" + // PagePrio field denotes page priority. + PagePrio = "page_prio" + // KstackBase field is the start address of the kernel space stack. + KstackBase = "kstack" + // KstackLimit field is the end address of the kernel space stack. + KstackLimit = "kstack_limit" + // UstackBase field is the start address of the user space stack. + UstackBase = "ustack" + // UstackLimit field is the end address of the user space stack. + UstackLimit = "ustack_limit" + // StartAddress field is the thread start address. + StartAddress = "start_address" + // StartAddressSymbol field is the symbol associated with the thread start address. + StartAddressSymbol = "start_address_symbol" + // StartAddressModule field is the module where the thread start address is mapped. + StartAddressModule = "start_address_module" + // TEB field is the address of the Thread Environment Block (TEB) + TEB = "teb" + + // FileObject determines the field name for the file object pointer. + FileObject = "file_object" + // FilePath represents the field that designates the absolute path of the file. + FilePath = "file_path" + // FileCreateOptions is the field that represents the values passed in the CreateDispositions parameter to the NtCreateFile function. + FileCreateOptions = "create_options" + // FileOperation is the field that represents the values passed in the CreateOptions parameter to the NtCreateFile function. + FileOperation = "create_disposition" + // FileCreated represents the name for the file creation field. + FileCreated = "created" + // FileAccessed represents the name for the file access field. + FileAccessed = "accessed" + // FileModified represents the name for the file modification field. + FileModified = "modified" + // FileShareMask represents the field name for the share access mask. + FileShareMask = "share_mask" + // FileType represents the field name that indicates the file type. + FileType = "type" + // FileAttributes is the field that represents file attribute values. + FileAttributes = "attributes" + // FileIoSize is the filed that represents the number of bytes in file read/write operations. + FileIoSize = "io_size" + // FileOffset represents the file for the file offset in read/write operations. + FileOffset = "offset" + // FileInfoClass represents the file information class. + FileInfoClass = "class" + // FileKey represents the directory key identifier in EnumDirectory events. + FileKey = "file_key" + // FileDirectory represents the field for the directory name in EnumDirectory events. + FileDirectory = "directory" + // FileIrpPtr represents the I/O request packet id. + FileIrpPtr = "irp" + // FileExtraInfo is the parameter that represents extra information returned by the file system for the operation. For example for a read request, the actual number of bytes that were read. + FileExtraInfo = "extra_info" + // FileIsDLL is the parameter that indicates if the file is a DLL + FileIsDLL = "is_dll" + // FileIsDriver is the parameter that indicates if the file is a driver + FileIsDriver = "is_driver" + // FileIsExecutable is the parameter that indicates if the file is an executable + FileIsExecutable = "is_exec" + // FileIsDotnet is the parameter that indicates if the file is a .NET assembly + FileIsDotnet = "is_dotnet" + + // FileViewBase is the parameter that represents the base address of the mapped section. + FileViewBase = "view_base" + // FileViewSize is the parameter that represents the size of the mapped section. + FileViewSize = "view_size" + // FileViewSectionType is the parameter that represents the mapped section type. + FileViewSectionType = "section_type" + + // RegKeyHandle identifies the parameter name for the registry key handle. + RegKeyHandle = "key_handle" + // RegKCB identifies the parameter name for the registry key control block. + RegKCB = "kcb" + // RegPath represents the parameter name for the fully qualified key path. + RegPath = "key_path" + // RegValue identifies the parameter name that contains the value + RegValue = "value" + // RegValueType identifies the parameter that represents registry value type e.g (DWORD, BINARY) + RegValueType = "value_type" + // RegData identifies the parameter that stores the captured registry data + RegData = "data" + + // ModuleBase identifies the parameter name for the base address of the process in which the Mmdule is loaded. + ModuleBase = "base_address" + // ModuleSize represents the parameter name for the size of the module in bytes. + ModuleSize = "module_size" + // ModuleCheckSum is the parameter name for module checksum. + ModuleCheckSum = "checksum" + // ModuleTimeDateStamp is the parametter name for module timedate stamp. + ModuleTimeDateStamp = "timedate_stamp" + // ModuleDefaultBase is the parameter name that represents module's base address. + ModuleDefaultBase = "default_address" + // ModulePath is the parameter name that denotes the file path and extension of the DLL/executable Module. + ModulePath = "file_path" + // ModuleSignatureLevel is the parameter denoting the loaded module signature level. + ModuleSignatureLevel = "signature_level" + // ModuleSignatureType is the parameter denoting the loaded module signature type. + ModuleSignatureType = "signature_type" + // ModuleCertSubject is the parameter that indicates the subject of the certificate is the entity its public key is associated with. + ModuleCertSubject = "cert_subject" + // ModuleCertIssuer is the parameter that represents the certificate authority (CA). + ModuleCertIssuer = "cert_issuer" + // ModuleCertSerial is the parameter that represents the serial number MUST be a positive integer assigned + // by the CA to each certificate. + ModuleCertSerial = "cert_serial" + // ModuleCertNotBefore is the parameter that specifies the certificate won't be valid before this timestamp. + ModuleCertNotBefore = "cert_not_before" + // ModuleCertNotAfter is the parameter that specifies the certificate won't be valid after this timestamp. + ModuleCertNotAfter = "cert_not_after" + + // NetSize identifies the parameter name that represents the packet size. + NetSize = "size" + // NetDIP is the parameter name that denotes the destination IP address. + NetDIP = "dip" + // NetSIP is the parameter name that denotes the source IP address. + NetSIP = "sip" + // NetDport identifies the parameter name that represents destination port number. + NetDport = "dport" + // NetSport identifies the parameter name that represents source port number. + NetSport = "sport" + // NetMSS is the parameter name that represents the maximum TCP segment size. + NetMSS = "mss" + // NetRcvWin is the parameter name that represents TCP segment's receive window size. + NetRcvWin = "rcvwin" + // NetSAckopt is the parameter name that represents Selective Acknowledgment option in TCP header. + NetSAckopt = "sack_opt" + // NetTsopt is the parameter name that represents the time stamp option in TCP header. + NetTsopt = "timestamp_opt" + // NetWsopt is the parameter name that represents the window scale option in TCP header. + NetWsopt = "window_scale_opt" + // NetRcvWinScale is the parameter name that represents the TCP receive window scaling factor. + NetRcvWinScale = "recv_winscale" + // NetSendWinScale is the parameter name that represents the TCP send window scaling factor. + NetSendWinScale = "send_winscale" + // NetSeqNum is the parameter name that represents the TCP sequence number. + NetSeqNum = "seqnum" + // NetStartTime is the parameter name that represents the TCP start time. + NetStartTime = "start_time" + // NetEndTime is the parameter name that represents the TCP end time. + NetEndTime = "end_time" + // NetConnID is the parameter name that represents a unique connection identifier. + NetConnID = "connid" + // NetL4Proto is the parameter name that identifies the Layer 4 protocol name. + NetL4Proto = "l4_proto" + // NetDportName is the field that denotes the destination port name. + NetDportName = "dport_name" + // NetSportName is the field that denotes the source port name. + NetSportName = "sport_name" + // NetSIPNames is the field that denotes the source IP address names. + NetSIPNames = "sip_names" + // NetDIPNames is the field that denotes the destination IP address names. + NetDIPNames = "dip_names" + + // DNSName is the field that represents the DNS query name + DNSName = "name" + // DNSRR is the field that represents the DNS record type + DNSRR = "rr" + // DNSOpts is the field that represents the DNS options + DNSOpts = "options" + // DNSRcode is the field that represents the DNS response code + DNSRcode = "rcode" + // DNSAnswers is the field that represents DNS response answers + DNSAnswers = "answers" + + // HandleID identifies the parameter that specifies the handle identifier. + HandleID = "handle_id" + // HandleSourceID identifies the parameter that specifies the source handle identifier. + HandleSourceID = "handle_source_id" + // HandleObject identifies the parameter that represents the kernel object to which handle is associated. + HandleObject = "handle_object" + // HandleObjectName identifies the parameter that represents the kernel object name. + HandleObjectName = "handle_name" + // HandleObjectTypeID identifies the parameter that represents the kernel object type identifier. + HandleObjectTypeID = "type_id" + + // MemBaseAddress identifies the parameter that denotes the allocation base address. + MemBaseAddress = "base_address" + // MemRegionSize identifies the parameter that represents the allocated region size. + MemRegionSize = "region_size" + // MemAllocType identifies the parameter that represents allocation flags. + MemAllocType = "alloc_type" + // MemProtect identifies the parameter that represents the memory protection for the range of pages. + MemProtect = "protection" + // MemProtectMask identifies the parameter that represents the memory protection in mask notation + MemProtectMask = "protection_mask" + // MemPageType identifies the parameter that represents the allocated region type. + MemPageType = "page_type" + + // LinkSource identifies the parameter that represents the source symbolic link object or other kernel object + LinkSource = "source" + // LinkTarget identifies the parameter that represents the target symbolic link object or other kernel object + LinkTarget = "target" + + // ThreadpoolPoolID represents the thread pool identifier. + ThreadpoolPoolID = "pool_id" + // ThreadpoolTaskID represents the thread pool task identifier. + ThreadpoolTaskID = "task_id" + // ThreadpoolCallback represents the address of the callback function. + ThreadpoolCallback = "callback" + // ThreadpoolCallbackSymbol represents the callback symbol. + ThreadpoolCallbackSymbol = "callback_symbol" + // ThreadpoolCallbackModule represents the module containing the callback symbol. + ThreadpoolCallbackModule = "callback_module" + // ThreadpoolContext represents the address of the callback context. + ThreadpoolContext = "context" + // ThreadpoolContextRip represents the value of instruction pointer contained in the callback context. + ThreadpoolContextRip = "context_rip" + // ThreadpoolContextRipSymbol represents the symbol name associated with the instruction pointer in callback context. + ThreadpoolContextRipSymbol = "context_rip_symbol" + // ThreadpoolContextRipModule represents the module name associated with the instruction pointer in callback context. + ThreadpoolContextRipModule = "context_rip_module" + // ThreadpoolSubprocessTag represents the service identifier associated with the thread pool. + ThreadpoolSubprocessTag = "subprocess_tag" + // ThreadpoolTimerDuetime represents the timer due time. + ThreadpoolTimerDuetime = "duetime" + // ThreadpoolTimerSubqueue represents the memory address of the timer subqueue. + ThreadpoolTimerSubqueue = "subqueue" + // ThreadpoolTimer represents the memory address of the timer object. + ThreadpoolTimer = "timer" + // ThreadpoolTimerPeriod represents the period of the timer + ThreadpoolTimerPeriod = "period" + // ThreadpoolTimerWindow represents the timer tolerate period. + ThreadpoolTimerWindow = "window" + // ThreadpoolTimerAbsolute indicates if the timer is absolute or relative. + ThreadpoolTimerAbsolute = "absolute" +) diff --git a/pkg/event/params/param_types.go b/pkg/event/params/param_types.go new file mode 100644 index 000000000..aec8c363d --- /dev/null +++ b/pkg/event/params/param_types.go @@ -0,0 +1,142 @@ +/* + * Copyright 2021-present by Nedim Sabic Sabic + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package params + +// Type defines event parameter type +type Type uint16 + +const ( + // Null is a null parameter type + Null Type = iota + // UnicodeString a string of 16-bit characters. By default, assumed to have been encoded using UTF-16LE + UnicodeString + // AnsiString a string of 8-bit characters + AnsiString + // Int8 a signed 8-bit integer + Int8 + // Uint8 an unsigned 8-bit integer + Uint8 + // Int16 a signed 16-bit integer + Int16 + // Uint16 an unsigned 16-bit integer + Uint16 + // Int32 a signed 32-bit integer + Int32 + // Uint32 an unsigned 32-bit integer + Uint32 + // Int64 a signed 64-bit integer + Int64 + // Uint64 an unsigned 64-bit integer + Uint64 + // Float an IEEE 4-byte floating-point number + Float + // Double an IEEE 8-byte floating-point number + Double + // Bool a 32-bit value where 0 is false and 1 is true + Bool + // Binary is a binary data of variable size. The size must be specified in the data definition as a constant or a reference to another (integer) data item.For an IP V6 address, the data should be an IN6_ADDR structure. + // For a socket address, the data should be a SOCKADDR_STORAGE structure. The AF_INET, AF_INET6, and AF_LINK address families are supported + Binary + // GUID is a GUID structure. On output, the GUID is rendered in the registry string form, {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} + GUID + // Pointer an unsigned 32-bit or 64-bit pointer value. The size depends on the architecture of the computer logging the event + Pointer + // SID a security identifier (SID) structure that uniquely identifies a user or group + SID + // PID is the process identifier + PID + // TID is the thread identifier + TID + // WbemSID is the Web-Based Enterprise Management security identifier. + WbemSID + // Port represents the endpoint port number + Port + // IP is the IP address + IP + // IPv4 is the IPv4 address + IPv4 + // IPv6 is the IPv6 address + IPv6 + // Time represents the timestamp + Time + // Slice represents a collection of items + Slice + // Enum represents an enumeration + Enum + // Map represents a map + Map + // Object is the generic object type + Object + // DOSPath represents the file system path in DOS device notation + DOSPath + // Path represents the file system path with normalized drive letter notation + Path + // Status represents the system error code message + Status + // Key represents the registry key + Key + // Flags represents a bitmask of flags + Flags + // Flags64 represents an extended (64 bits) bitmask of flags + Flags64 + // Address is the memory address reference + Address + // HandleType represents the handle type such as Mutex or File + HandleType +) + +// String return the type string representation. +func (t Type) String() string { + switch t { + case UnicodeString: + return "unicode" + case AnsiString: + return "ansi" + case Int8: + return "int8" + case Uint8: + return "uint8" + case Int16: + return "int16" + case Uint16: + return "uint16" + case Int32: + return "int32" + case Uint32: + return "uint32" + case Int64: + return "int64" + case Uint64: + return "uint64" + case SID, WbemSID: + return "sid" + case TID: + return "tid" + case PID: + return "pid" + case Port: + return "port" + case IPv6: + return "ipv6" + case IPv4: + return "ipv4" + default: + return "unknown" + } +} diff --git a/pkg/event/queue_test.go b/pkg/event/queue_test.go index cd3fed7a0..05ee7f262 100644 --- a/pkg/event/queue_test.go +++ b/pkg/event/queue_test.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2021-2022 by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/pkg/event/stackwalk.go b/pkg/event/stackwalk.go index 752ae39ad..21077ab01 100644 --- a/pkg/event/stackwalk.go +++ b/pkg/event/stackwalk.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2021-present by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/pkg/event/stackwalk_test.go b/pkg/event/stackwalk_test.go index 285070555..c624151a8 100644 --- a/pkg/event/stackwalk_test.go +++ b/pkg/event/stackwalk_test.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2021-present by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/pkg/filter/fields/defs.go b/pkg/filter/fields/defs.go new file mode 100644 index 000000000..5743682ce --- /dev/null +++ b/pkg/filter/fields/defs.go @@ -0,0 +1,1304 @@ +/* + * Copyright 2019-2020 by Nedim Sabic Sabic + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package fields + +import ( + "strings" + "unicode" + + "github.com/rabbitstack/fibratus/pkg/event/params" +) + +// Field represents the type alias for the field +type Field string + +const ( + // PsPid represents the process id field + PsPid Field = "ps.pid" + // PsPpid represents the parent process id field + PsPpid Field = "ps.ppid" + // PsName represents the process name field + PsName Field = "ps.name" + // PsComm represents the process command line field. Deprecated. + PsComm Field = "ps.comm" + // PsCmdline represents the process command line field + PsCmdline Field = "ps.cmdline" + // PsExe represents the process image path field + PsExe Field = "ps.exe" + // PsArgs represents the process command line arguments + PsArgs Field = "ps.args" + // PsCwd represents the process current working directory + PsCwd Field = "ps.cwd" + // PsSID represents the process security identifier + PsSID Field = "ps.sid" + // PsDomain represents the process domain field + PsDomain Field = "ps.domain" + // PsUsername represents the process username field + PsUsername Field = "ps.username" + // PsSessionID represents the session id bound to the process + PsSessionID Field = "ps.sessionid" + // PsEnvs represents the process environment variables + PsEnvs Field = "ps.envs" + // PsHandleNames represents the process handles + PsHandleNames Field = "ps.handles" + // PsHandleTypes represents the process handle types + PsHandleTypes Field = "ps.handle.types" + // PsDTB represents the process directory table base address + PsDTB Field = "ps.dtb" + // PsModuleNames represents the process module file names + PsModuleNames Field = "ps.modules" + // PsParentPid represents the parent process identifier field + PsParentPid Field = "ps.parent.pid" + // PsParentName represents the parent process name field + PsParentName Field = "ps.parent.name" + // PsParentComm represents the parent process command line field. Deprecated + PsParentComm Field = "ps.parent.comm" + // PsParentCmdline represents the parent process command line field + PsParentCmdline Field = "ps.parent.cmdline" + // PsParentExe represents the parent process image path field + PsParentExe Field = "ps.parent.exe" + // PsParentArgs represents the parent process command line arguments field + PsParentArgs Field = "ps.parent.args" + // PsParentCwd represents the parent process current working directory field + PsParentCwd Field = "ps.parent.cwd" + // PsParentSID represents the parent process security identifier field + PsParentSID Field = "ps.parent.sid" + // PsParentUsername represents the parent process username field + PsParentUsername Field = "ps.parent.username" + // PsParentDomain represents the parent process domain field + PsParentDomain Field = "ps.parent.domain" + // PsParentSessionID represents the session id field bound to the parent process + PsParentSessionID Field = "ps.parent.sessionid" + // PsParentEnvs represents the parent process environment variables field + PsParentEnvs Field = "ps.parent.envs" + // PsParentHandles represents the parent process handles field + PsParentHandles Field = "ps.parent.handles" + // PsParentHandleTypes represents the parent process handle types field + PsParentHandleTypes Field = "ps.parent.handle.types" + // PsParentDTB represents the parent process directory table base address field + PsParentDTB Field = "ps.parent.dtb" + // PsAncestor represents the process ancestor field + PsAncestor Field = "ps.ancestor" + // PsAccessMask represents the process access rights field + PsAccessMask Field = "ps.access.mask" + // PsAccessMaskNames represents the process access rights list field + PsAccessMaskNames Field = "ps.access.mask.names" + // PsAccessStatus represents the process access status field + PsAccessStatus Field = "ps.access.status" + // PsIsWOW64Field represents the field that indicates if the 32-bit process is created in 64-bit Windows system + PsIsWOW64Field Field = "ps.is_wow64" + // PsIsPackagedField represents the field that indicates if a process is packaged with the MSIX technology + PsIsPackagedField Field = "ps.is_packaged" + // PsIsProtectedField represents the field that indicates if the process is to be run as a protected process + PsIsProtectedField Field = "ps.is_protected" + // PsParentIsWOW64Field represents the field that indicates if the 32-bit process is created in 64-bit Windows system + PsParentIsWOW64Field Field = "ps.parent.is_wow64" + // PsParentIsPackagedField represents the field that indicates if a process is packaged with the MSIX technology + PsParentIsPackagedField Field = "ps.parent.is_packaged" + // PsParentIsProtectedField represents the field that indicates if the process is to be run as a protected process + PsParentIsProtectedField Field = "ps.parent.is_protected" + // PsUUID represents the unique process identifier + PsUUID Field = "ps.uuid" + // PsParentUUID represents the unique parent process identifier + PsParentUUID Field = "ps.parent.uuid" + // PsTokenIntegrityLevel represents the field that indicates the current process integrity level + PsTokenIntegrityLevel = "ps.token.integrity_level" + // PsTokenIsElevated represents the field that indicates if the current process token is elevated + PsTokenIsElevated = "ps.token.is_elevated" + // PsTokenElevationType represents the field that indicates if the current process token elevation type + PsTokenElevationType = "ps.token.elevation_type" + // PsParentTokenIntegrityLevel represents the field that indicates the parent process integrity level + PsParentTokenIntegrityLevel = "ps.parent.token.integrity_level" + // PsParentTokenIsElevated represents the field that indicates if the parent process token is elevated + PsParentTokenIsElevated = "ps.parent.token.is_elevated" + // PsTokenElevationType represents the field that indicates if the parent process token elevation type + PsParentTokenElevationType = "ps.parent.token.elevation_type" + // PsSignatureExists is the field which indicates if the binary is signed, either by embedded or catalog signature + PsSignatureExists Field = "ps.signature.exists" + // PsSignatureTrusted is the field which indicates if the binary signature is trusted + PsSignatureTrusted Field = "ps.signature.trusted" + // PsSignatureIssuer is the field which indicates the certificate issuer + PsSignatureIssuer Field = "ps.signature.issuer" + // PsSignatureSubject is the field which indicates the certificate subject + PsSignatureSubject Field = "ps.signature.subject" + // PsSignatureSerial is the field which indicates the certificate serial + PsSignatureSerial Field = "ps.signature.serial" + // PsSignatureAfter is the field which indicates the timestamp after certificate is no longer valid + PsSignatureAfter Field = "ps.signature.after" + // PsSignatureBefore is the field which indicates the timestamp of the certificate enrollment date + PsSignatureBefore Field = "ps.signature.before" + + // PsPeNumSections represents the number of sections + PsPeNumSections Field = "ps.pe.nsections" + // PsPeNumSymbols represents the number of exported symbols + PsPeNumSymbols Field = "ps.pe.nsymbols" + // PsPeSymbols represents imported symbols + PsPeSymbols Field = "ps.pe.symbols" + // PeImports represents imported libraries (e.g. kernel32.dll) + PsPeImports Field = "ps.pe.imports" + // PeTimestamp is the PE build timestamp + PsPeTimestamp Field = "ps.pe.timestamp" + // PeBaseAddress represents the base address when the binary is loaded + PsPeBaseAddress Field = "ps.pe.address.base" + // PeEntrypoint is the address of the entrypoint function + PsPeEntrypoint Field = "ps.pe.address.entrypoint" + // PeResources represents PE resources + PsPeResources Field = "ps.pe.resources" + // PeCompany represents the company name resource + PsPeCompany Field = "ps.pe.company" + // PeDescription represents the internal description of the file + PsPeDescription Field = "ps.pe.description" + // PeFileVersion represents the internal file version + PsPeFileVersion Field = "ps.pe.file.version" + // PeFileName represents the original file name provided at compile-time. + PsPeFileName Field = "ps.pe.file.name" + // PeCopyright represents the copyright notice emitted at compile-time + PsPeCopyright Field = "ps.pe.copyright" + // PeProduct represents the product name provided at compile-time + PsPeProduct Field = "ps.pe.product" + // PeProductVersion represents the internal product version provided at compile-time + PsPeProductVersion Field = "ps.pe.product.version" + // PeAnomalies represents the field that contains PE anomalies detected during parsing + PsPeAnomalies Field = "ps.pe.anomalies" + // PsPeImphash is the field that yields the PE import hash + PsPeImphash Field = "ps.pe.imphash" + // PsPeIsDotnet is the field which indicates if the binary contains the .NET assembly + PsPeIsDotnet Field = "ps.pe.is_dotnet" + // PsPeIsModified is the field that indicates whether disk and in-memory PE headers differ + PsPeIsModified Field = "ps.pe.is_modified" + + // ThreadBasePrio is the base thread priority + ThreadBasePrio Field = "thread.prio" + // ThreadIOPrio is the thread I/O priority + ThreadIOPrio Field = "thread.io.prio" + // ThreadPagePrio is the thread page priority + ThreadPagePrio Field = "thread.page.prio" + // ThreadKstackBase is the thread kernel stack start address + ThreadKstackBase Field = "thread.kstack.base" + // ThreadKstackLimit is the thread kernel stack end address + ThreadKstackLimit Field = "thread.kstack.limit" + // ThreadUstackBase is the thread user stack start address + ThreadUstackBase Field = "thread.ustack.base" + // ThreadUstackLimit is the thead user stack end address + ThreadUstackLimit Field = "thread.ustack.limit" + // ThreadEntrypoint is the thread entrypoint address + ThreadEntrypoint Field = "thread.entrypoint" + // ThreadStartAddress is the thread start address + ThreadStartAddress Field = "thread.start_address" + // ThreadPID is the process identifier where the thread is created + ThreadPID Field = "thread.pid" + // ThreadTEB is the thread environment block base address + ThreadTEB Field = "thread.teb_address" + // ThreadAccessMask represents the thread access rights field + ThreadAccessMask Field = "thread.access.mask" + // ThreadAccessMaskNames represents the thread access rights list field + ThreadAccessMaskNames Field = "thread.access.mask.names" + // ThreadAccessStatus represents the thread access status field + ThreadAccessStatus Field = "thread.access.status" + // ThreadCallstackSummary represents the thread callstack summary field + ThreadCallstackSummary Field = "thread.callstack.summary" + // ThreadCallstackKernelSummary represents the kernel thread callstack summary field + ThreadCallstackKernelSummary Field = "thread.callstack.kernel_summary" + // ThreadCallstackDetail represents the thread callstack detail field + ThreadCallstackDetail Field = "thread.callstack.detail" + // ThreadCallstackModules represents the callstack modules field + ThreadCallstackModules Field = "thread.callstack.modules" + // ThreadCallstackSymbols represents the callstack symbols field + ThreadCallstackSymbols Field = "thread.callstack.symbols" + // ThreadCallstackProtections represents the callstack region protections field + ThreadCallstackProtections Field = "thread.callstack.protections" + // ThreadCallstackAllocationSizes represents the private region page sizes field + ThreadCallstackAllocationSizes Field = "thread.callstack.allocation_sizes" + // ThreadCallstackCallsiteLeadingAssembly represents the callsite prelude opcodes field + ThreadCallstackCallsiteLeadingAssembly Field = "thread.callstack.callsite_leading_assembly" + // ThreadCallstackCallsiteTrailingAssembly represents the callsite postlude opcodes field + ThreadCallstackCallsiteTrailingAssembly Field = "thread.callstack.callsite_trailing_assembly" + // ThreadCallstackIsUnbacked represents the field that indicates if there is an unbacked stack frame + ThreadCallstackIsUnbacked Field = "thread.callstack.is_unbacked" + // ThreadStartAddressSymbol represents the symbol corresponding to the thread start address + ThreadStartAddressSymbol Field = "thread.start_address.symbol" + // ThreadStartAddressModule represents the module corresponding to the thread start address + ThreadStartAddressModule Field = "thread.start_address.module" + // ThreadCallstackAddresses represents the all callstack return addresses + ThreadCallstackAddresses Field = "thread.callstack.addresses" + // ThreadCallstackFinalUserModuleName represents the final user space stack frame module name + ThreadCallstackFinalUserModuleName Field = "thread.callstack.final_user_module.name" + // ThreadCallstackFinalUserModulePath represents the final user space stack frame module path + ThreadCallstackFinalUserModulePath Field = "thread.callstack.final_user_module.path" + // ThreadCallstackFinalUserSymbolName represents the final user space stack frame symbol name + ThreadCallstackFinalUserSymbolName Field = "thread.callstack.final_user_symbol.name" + // ThreadCallstackFinalKernelModuleName represents the final kernel space stack frame module name + ThreadCallstackFinalKernelModuleName Field = "thread.callstack.final_kernel_module.name" + // ThreadCallstackFinalKernelModulePath represents the final kernel space stack frame module name + ThreadCallstackFinalKernelModulePath Field = "thread.callstack.final_kernel_module.path" + // ThreadCallstackFinalKernelSymbolName represents the final kernel space stack frame symbol name + ThreadCallstackFinalKernelSymbolName Field = "thread.callstack.final_kernel_symbol.name" + // ThreadCallstackFinalUserModuleSignatureExists represents the signature status of the final user space stack frame module + ThreadCallstackFinalUserModuleSignatureExists Field = "thread.callstack.final_user_module.signature.exists" + // ThreadCallstackFinalUserModuleSignatureTrusted represents the trust status of the final user space stack frame module signature + ThreadCallstackFinalUserModuleSignatureTrusted Field = "thread.callstack.final_user_module.signature.trusted" + // ThreadCallstackFinalUserModuleSignatureIssuer represents the final user space stack frame module certificate issuer + ThreadCallstackFinalUserModuleSignatureIssuer Field = "thread.callstack.final_user_module.signature.issuer" + // ThreadCallstackFinalUserModuleSignatureSubject represents the final user space stack frame module certificate subject + ThreadCallstackFinalUserModuleSignatureSubject Field = "thread.callstack.final_user_module.signature.subject" + + // PeNumSections represents the number of sections + PeNumSections Field = "pe.nsections" + // PeNumSymbols represents the number of exported symbols + PeNumSymbols Field = "pe.nsymbols" + // PeSymbols represents imported symbols + PeSymbols Field = "pe.symbols" + // PeImports represents imported libraries (e.g. kernel32.dll) + PeImports Field = "pe.imports" + // PeTimestamp is the PE build timestamp + PeTimestamp Field = "pe.timestamp" + // PeBaseAddress represents the base address when the binary is loaded + PeBaseAddress Field = "pe.address.base" + // PeEntrypoint is the address of the entrypoint function + PeEntrypoint Field = "pe.address.entrypoint" + // PeResources represents PE resources + PeResources Field = "pe.resources" + // PeCompany represents the company name resource + PeCompany Field = "pe.company" + // PeDescription represents the internal description of the file + PeDescription Field = "pe.description" + // PeFileVersion represents the internal file version + PeFileVersion Field = "pe.file.version" + // PeFileName represents the original file name provided at compile-time. + PeFileName Field = "pe.file.name" + // PeCopyright represents the copyright notice emitted at compile-time + PeCopyright Field = "pe.copyright" + // PeProduct represents the product name provided at compile-time + PeProduct Field = "pe.product" + // PeProductVersion represents the internal product version provided at compile-time + PeProductVersion Field = "pe.product.version" + // PeIsDLL indicates if the file is a DLL + PeIsDLL Field = "pe.is_dll" + // PeIsDriver indicates if the file is a driver + PeIsDriver Field = "pe.is_driver" + // PeIsExecutable indicates if the file is an executable + PeIsExecutable Field = "pe.is_exec" + // PeAnomalies represents the field that contains PE anomalies detected during parsing + PeAnomalies Field = "pe.anomalies" + // PeImphash is the field that yields the PE import hash + PeImphash Field = "pe.imphash" + // PeIsDotnet is the field which indicates if the binary contains the .NET assembly + PeIsDotnet Field = "pe.is_dotnet" + // PeIsSigned is the field which indicates if the binary is signed, either by embedded or catalog signature + PeIsSigned Field = "pe.is_signed" + // PeIsTrusted is the field which indicates if the binary signature is trusted + PeIsTrusted Field = "pe.is_trusted" + // PeCertIssuer is the field which indicates the certificate issuer + PeCertIssuer Field = "pe.cert.issuer" + // PeCertSubject is the field which indicates the certificate subject + PeCertSubject Field = "pe.cert.subject" + // PeCertSerial is the field which indicates the certificate serial + PeCertSerial Field = "pe.cert.serial" + // PeCertAfter is the field which indicates the timestamp after certificate is no longer valid + PeCertAfter Field = "pe.cert.after" + // PeCertBefore is the field which indicates the timestamp of the certificate enrollment date + PeCertBefore Field = "pe.cert.before" + // PeIsModified is the field that indicates whether disk and in-memory PE headers differ + PeIsModified Field = "pe.is_modified" + + // EvtSeq is the event sequence number + EvtSeq Field = "evt.seq" + // EvtPID is the process identifier that generated the event + EvtPID Field = "evt.pid" + // EvtTID is the thread identifier that generated the event + EvtTID Field = "evt.tid" + // EvtCPU is the CPU core where the event was generated + EvtCPU Field = "evt.cpu" + // EvtDesc represents the event description + EvtDesc Field = "evt.desc" + // EvtHost represents the host where the event was produced + EvtHost Field = "evt.host" + // EvtTime is the event time + EvtTime Field = "evt.time" + // EvtTimeHour is the hour part of the event time + EvtTimeHour Field = "evt.time.h" + // EvtTimeMin is the minute part of the event time + EvtTimeMin Field = "evt.time.m" + // EvtTimeSec is the second part of the event time + EvtTimeSec Field = "evt.time.s" + // EvtTimeNs is the nanosecond part of the event time + EvtTimeNs Field = "evt.time.ns" + // EvtDate is the event date + EvtDate Field = "evt.date" + // EvtDateDay is the day of event date + EvtDateDay Field = "evt.date.d" + // EvtDateMonth is the month of event date + EvtDateMonth Field = "evt.date.m" + // EvtDateYear is the year of event date + EvtDateYear Field = "evt.date.y" + // EvtDateTz is the time zone of event timestamp + EvtDateTz Field = "evt.date.tz" + // EvtDateWeek is the event week number + EvtDateWeek Field = "evt.date.week" + // EvtDateWeekday is the event week day + EvtDateWeekday Field = "evt.date.weekday" + // EvtName is the event name + EvtName Field = "evt.name" + // EvtCategory is the event category + EvtCategory Field = "evt.category" + // EvtNparams is the number of event parameters + EvtNparams Field = "evt.nparams" + // EvtArg represents the field sequence for generic argument access + EvtArg Field = "evt.arg" + // EvtIsDirectSyscall represents the field that designates if this event is + // performing a direct syscall. + EvtIsDirectSyscall Field = "evt.is_direct_syscall" + // EvtIsIndirectSyscall represents the field that designates if this event is + // performing an indirect syscall. + EvtIsIndirectSyscall Field = "evt.is_indirect_syscall" + + // KevtSeq is the event sequence number + KevtSeq Field = "kevt.seq" + // KevtPID is the process identifier that generated the event + KevtPID Field = "kevt.pid" + // KevtTID is the thread identifier that generated the event + KevtTID Field = "kevt.tid" + // KevtCPU is the CPU core where the event was generated + KevtCPU Field = "kevt.cpu" + // KevtDesc represents the event description + KevtDesc Field = "kevt.desc" + // KevtHost represents the host where the event was produced + KevtHost Field = "kevt.host" + // KevtTime is the event time + KevtTime Field = "kevt.time" + // KevtTimeHour is the hour part of the event time + KevtTimeHour Field = "kevt.time.h" + // KevtTimeMin is the minute part of the event time + KevtTimeMin Field = "kevt.time.m" + // KevtTimeSec is the second part of the event time + KevtTimeSec Field = "kevt.time.s" + // KevtTimeNs is the nanosecond part of the event time + KevtTimeNs Field = "kevt.time.ns" + // KevtDate is the event date + KevtDate Field = "kevt.date" + // KevtDateDay is the day of event date + KevtDateDay Field = "kevt.date.d" + // KevtDateMonth is the month of event date + KevtDateMonth Field = "kevt.date.m" + // KevtDateYear is the year of event date + KevtDateYear Field = "kevt.date.y" + // KevtDateTz is the time zone of event timestamp + KevtDateTz Field = "kevt.date.tz" + // KevtDateWeek is the event week number + KevtDateWeek Field = "kevt.date.week" + // KevtDateWeekday is the event week day + KevtDateWeekday Field = "kevt.date.weekday" + // KevtName is the event name + KevtName Field = "kevt.name" + // KevtCategory is the event category + KevtCategory Field = "kevt.category" + // KevtNparams is the number of event parameters + KevtNparams Field = "kevt.nparams" + // KevtArg represents the field sequence for generic argument access + KevtArg Field = "kevt.arg" + + // HandleID represents the handle identifier within the process address space + HandleID Field = "handle.id" + // HandleObject represents the handle object address + HandleObject Field = "handle.object" + // HandleName represents the handle name + HandleName Field = "handle.name" + // HandleType represents the handle type (e.g. file) + HandleType Field = "handle.type" + + // NetDIP represents network destination IP address + NetDIP Field = "net.dip" + // NetSIP represents the source IP address + NetSIP Field = "net.sip" + // NetDport represents the destination port + NetDport Field = "net.dport" + // NetSport represents the source port + NetSport Field = "net.sport" + // NetDportName represents the destination port IANA name + NetDportName Field = "net.dport.name" + // NetSportName represents the source port IANA name + NetSportName Field = "net.sport.name" + // NetL4Proto represents the Layer4 protocol name (e.g. TCP) + NetL4Proto Field = "net.l4.proto" + // NetPacketSize represents the packet size + NetPacketSize Field = "net.size" + // NetSIPNames represents the source IP names + NetSIPNames Field = "net.sip.names" + // NetDIPNames represents the destination IP names + NetDIPNames Field = "net.dip.names" + + // FileObject represents the address of the file object + FileObject Field = "file.object" + // FileName represents the file base name (e.g. cmd.exe) + FileName Field = "file.name" + // FilePath represents the file full path (e.g. C:\Windows\System32\cmd.exe) + FilePath Field = "file.path" + // FilePathStem represents the full file path without extension (e.g. C:\Windows\System32\cmd) + FilePathStem Field = "file.path.stem" + // FileExtension represents the file extension (e.g. .exe or .dll) + FileExtension Field = "file.extension" + // FileOperation represents the file operation (e.g. create) + FileOperation Field = "file.operation" + // FileShareMask represents the file share mask + FileShareMask Field = "file.share.mask" + // FileShareMode represents the file share mode field + FileShareMode Field = "file.share_mode" + // FileIOSize represents the number of read/written bytes + FileIOSize Field = "file.io.size" + // FileOffset represents the read/write offset + FileOffset Field = "file.offset" + // FileType represents the file type + FileType Field = "file.type" + // FileAttributes represents a slice of file attributes + FileAttributes Field = "file.attributes" + // FileStatus represents the status message of the file operation + FileStatus Field = "file.status" + // FileViewBase represents the base address of the mapped view + FileViewBase Field = "file.view.base" + // FileViewSize represents the size of the mapped view + FileViewSize Field = "file.view.size" + // FileViewType represents the type of the mapped view section + FileViewType Field = "file.view.type" + // FileViewProtection represents the protection attributes of the section view + FileViewProtection Field = "file.view.protection" + // FileIsDLL indicates if the created file is a DLL + FileIsDLL Field = "file.is_dll" + // FileIsDriver indicates if the created file is a driver + FileIsDriver Field = "file.is_driver" + // FileIsExecutable indicates if the created file is an executable + FileIsExecutable Field = "file.is_exec" + // FilePID represents the field that denotes the process id performing file operations + FilePID Field = "file.pid" + // FileKey represents the field that uniquely identifies the file object. + FileKey Field = "file.key" + // FileInfoClass represents the field that identifies the file information class + FileInfoClass Field = "file.info_class" + // FileInfoAllocationSize represents the field that contains the file allocation size + FileInfoAllocationSize Field = "file.info.allocation_size" + // FileInfoEOFSize represents the field that contains the EOF size + FileInfoEOFSize Field = "file.info.eof_size" + // FileInfoIsDispositionDeleteFile represents the field that indicates if the file is deleted when its handle is closed + FileInfoIsDispositionDeleteFile Field = "file.info.is_disposition_delete_file" + + // RegistryPath represents the full registry path + RegistryPath Field = "registry.path" + // RegistryKeyName represents the registry key name + RegistryKeyName Field = "registry.key.name" + // RegistryKCB represents the registry KCB address + RegistryKCB Field = "registry.kcb" + // RegistryValue represents the registry value name field + RegistryValue Field = "registry.value" + // RegistryValueType represents the registry value type field + RegistryValueType Field = "registry.value.type" + // RegistryData represents the captured registry data field + RegistryData Field = "registry.data" + // RegistryStatus represent the registry operation status + RegistryStatus Field = "registry.status" + + // ImageBase is the module base address + ImageBase Field = "image.base.address" + // ImageSize is the module size + ImageSize Field = "image.size" + // ImageChecksum represents the module checksum hash + ImageChecksum Field = "image.checksum" + // ImageDefaultAddress represents the module address + ImageDefaultAddress Field = "image.default.address" + // ImagePath is the module full path + ImagePath Field = "image.path" + // ImageName is the module name + ImageName Field = "image.name" + // ImagePID is the pid of the process where the image was loaded + ImagePID Field = "image.pid" + // ImageSignatureType represents the image signature type + ImageSignatureType Field = "image.signature.type" + // ImageSignatureLevel represents the image signature level + ImageSignatureLevel Field = "image.signature.level" + // ImageCertSubject is the field that indicates the subject of the certificate is the entity its public key is associated with. + ImageCertSubject = "image.cert.subject" + // ImageCertIssuer is the field that represents the certificate authority (CA). + ImageCertIssuer = "image.cert.issuer" + // ImageCertSerial is the field that represents the serial number MUST be a positive integer assigned + // by the CA to each certificate. + ImageCertSerial = "image.cert.serial" + // ImageCertBefore is the field that specifies the certificate won't be valid before this timestamp. + ImageCertBefore = "image.cert.before" + // ImageCertAfter is the field that specifies the certificate won't be valid after this timestamp. + ImageCertAfter = "image.cert.after" + // ImageIsDLL indicates if the loaded image is a DLL + ImageIsDLL Field = "image.is_dll" + // ImageIsDriver indicates if the loaded image is a driver + ImageIsDriver Field = "image.is_driver" + // ImageIsExecutable indicates if the loaded image is an executable + ImageIsExecutable Field = "image.is_exec" + // ImageIsDotnet indicates if the loaded image is a .NET assembly + ImageIsDotnet Field = "image.is_dotnet" + + // DllBase is the DLL base address + DllBase Field = "dll.base" + // DllSize is the DLL virtual mapped space size + DllSize Field = "dll.size" + // DllPath is the DLL full path + DllPath Field = "dll.path" + // DllPath is the DLL path stem field + DllPathStem Field = "dll.path.stem" + // DllName is the DLL name + DllName Field = "dll.name" + // DllPID is the pid of the process where the DLL was loaded + DllPID Field = "dll.pid" + // DllSignatureType represents the DLL signature type + DllSignatureType Field = "dll.signature.type" + // DllSignatureLevel represents the DLL signature level + DllSignatureLevel Field = "dll.signature.level" + // DllSignatureExists is the field that determines if the DLL signature exists + DllSignatureExists Field = "dll.signature.exists" + // DllSignatureTrusted is the filed that determines if the DLL signature is trusted + DllSignatureTrusted Field = "dll.signature.trusted" + // DllSignatureSubject is the field that indicates the subject of the certificate is the entity its public key is associated with. + DllSignatureSubject = "dll.signature.subject" + // DllSignatureIssuer is the field that represents the certificate authority (CA). + DllSignatureIssuer = "dll.signature.issuer" + // DllSignatureSerial is the field that represents the serial number MUST be a positive integer assigned + // by the CA to each certificate. + DllSignatureSerial = "dll.signature.serial" + // DllSignatureBefore is the field that specifies the certificate won't be valid before this timestamp. + DllSignatureBefore = "dll.signature.before" + // DllSignatureAfter is the field that specifies the certificate won't be valid after this timestamp. + DllSignatureAfter = "dll.signature.after" + // DllIsDotnet indicates if the DLL is a .NET assembly. + DllIsDotnet Field = "dll.pe.is_dotnet" + + // ModuleBase is the module base address + ModuleBase Field = "module.base" + // ModuleSize is the module size + ModuleSize Field = "module.size" + // ModuleChecksum represents the module checksum hash + ModuleChecksum Field = "module.checksum" + // ModuleDefaultAddress represents the module address + ModuleDefaultAddress Field = "module.default_address" + // ModulePath is the module full path + ModulePath Field = "module.path" + // ModulePathStem is the module path stem field + ModulePathStem Field = "module.path.stem" + // ModuleName is the module name + ModuleName Field = "module.name" + // ModulePID is the pid of the process where the module was loaded + ModulePID Field = "module.pid" + // ModuleSignatureType represents the module signature type + ModuleSignatureType Field = "module.signature.type" + // ModuleSignatureLevel represents the module signature level + ModuleSignatureLevel Field = "module.signature.level" + // ModuleSignatureExists is the field that determines if the module signature exists + ModuleSignatureExists Field = "module.signature.exists" + // ModuleSignatureTrusted is the filed that determines if the module signature is trusted + ModuleSignatureTrusted Field = "module.signature.trusted" + // ModuleSignatureSubject is the field that indicates the subject of the certificate is the entity its public key is associated with. + ModuleSignatureSubject = "module.signature.subject" + // ModuleSignatureIssuer is the field that represents the certificate authority (CA). + ModuleSignatureIssuer = "module.signature.issuer" + // ModuleSignatureSerial is the field that represents the serial number MUST be a positive integer assigned + // by the CA to each certificate. + ModuleSignatureSerial = "module.signature.serial" + // ModuleSignatureBefore is the field that specifies the certificate won't be valid before this timestamp. + ModuleSignatureBefore = "module.signature.before" + // ModuleSignatureAfter is the field that specifies the certificate won't be valid after this timestamp. + ModuleSignatureAfter = "module.signature.after" + // ModuleIsDLL indicates if the loaded module is a DLL + ModuleIsDLL Field = "module.is_dll" + // ModuleIsDriver indicates if the loaded module is a driver + ModuleIsDriver Field = "module.is_driver" + // ModuleIsExecutable indicates if the loaded module is an executable + ModuleIsExecutable Field = "module.is_exec" + // ModuleIsDotnet indicates if the loaded module is a .NET assembly + ModuleIsDotnet Field = "module.pe.is_dotnet" + + // MemBaseAddress identifies the field that denotes the allocation base address + MemBaseAddress Field = "mem.address" + // MemRegionSize Field identifies the field that represents the allocated region size + MemRegionSize Field = "mem.size" + // MemAllocType identifies the field that represents region allocation type + MemAllocType Field = "mem.alloc" + // MemPageType identifies the parameter that represents the allocated region type + MemPageType Field = "mem.type" + // MemProtection identifies the field that represents the memory protection for the range of pages + MemProtection Field = "mem.protection" + // MemProtectionMask identifies the field that represents the memory protection in mask notation + MemProtectionMask Field = "mem.protection.mask" + + // DNSName identifies the field that represents the DNS name + DNSName Field = "dns.name" + // DNSRR identifies the field that represents the DNS record type + DNSRR Field = "dns.rr" + // DNSOptions identifies the field that represents the DNS options + DNSOptions Field = "dns.options" + // DNSAnswers identifies the field that represents the DNS answers + DNSAnswers Field = "dns.answers" + // DNSRcode identifies the field that represents the DNS response code + DNSRcode Field = "dns.rcode" + + // ThreadpoolPoolID identifies the field that represents the thread pool identifier + ThreadpoolPoolID = "threadpool.id" + // ThreadpoolTaskID identifies the field that represents the thread pool task identifier + ThreadpoolTaskID = "threadpool.task.id" + // ThreadpoolCallbackAddress identifies the field that represents the address of the callback function + ThreadpoolCallbackAddress = "threadpool.callback.address" + // ThreadpoolCallbackSymbol identifies the field that represents the callback symbol + ThreadpoolCallbackSymbol = "threadpool.callback.symbol" + // ThreadpoolCallbackModule identifies the field that represents the module containing the callback symbol + ThreadpoolCallbackModule = "threadpool.callback.module" + // ThreadpoolCallbackContext identifies the field that represents the address of the callback context + ThreadpoolCallbackContext = "threadpool.callback.context" + // ThreadpoolCallbackContextRip identifies the field that represents the value of instruction pointer contained in the callback context + ThreadpoolCallbackContextRip = "threadpool.callback.context.rip" + // ThreadpoolCallbackContextRipSymbol identifies the field that represents the symbol name associated with the instruction pointer in callback context + ThreadpoolCallbackContextRipSymbol = "threadpool.callback.context.rip.symbol" + // ThreadpoolCallbackContextRipModule identifies the field that represents the module name associated with the instruction pointer in callback context + ThreadpoolCallbackContextRipModule = "threadpool.callback.context.rip.module" + // ThreadpoolSubprocessTag identifies the field that represents the service identifier associated with the thread pool + ThreadpoolSubprocessTag = "threadpool.subprocess_tag" + // ThreadpoolTimerDuetime identifies the field that represents the timer due time + ThreadpoolTimerDuetime = "threadpool.timer.duetime" + // ThreadpoolTimerSubqueue identifies the field that represents the memory address of the timer subqueue + ThreadpoolTimerSubqueue = "threadpool.timer.subqueue" + // ThreadpoolTimer identifies the field that represents the memory address of the timer object + ThreadpoolTimer = "threadpool.timer.address" + // ThreadpoolTimerPeriod identifies the field that represents the period of the timer + ThreadpoolTimerPeriod = "threadpool.timer.period" + // ThreadpoolTimerWindow identifies the field that represents the timer tolerate period + ThreadpoolTimerWindow = "threadpool.timer.window" + // ThreadpoolTimerAbsolute identifies the field that indicates if the timer is absolute or relative + ThreadpoolTimerAbsolute = "threadpool.timer.is_absolute" +) + +// String casts the field type to string. +func (f Field) String() string { return string(f) } + +// Type returns the data type that this field contains. +func (f Field) Type() params.Type { return fields[f].Type } + +func (f Field) IsPsField() bool { return strings.HasPrefix(string(f), "ps.") } +func (f Field) IsKevtField() bool { return strings.HasPrefix(string(f), "kevt.") } +func (f Field) IsEvtField() bool { return strings.HasPrefix(string(f), "evt.") } +func (f Field) IsThreadField() bool { return strings.HasPrefix(string(f), "thread.") } +func (f Field) IsImageField() bool { return strings.HasPrefix(string(f), "image.") } +func (f Field) IsFileField() bool { return strings.HasPrefix(string(f), "file.") } +func (f Field) IsRegistryField() bool { return strings.HasPrefix(string(f), "registry.") } +func (f Field) IsNetworkField() bool { return strings.HasPrefix(string(f), "net.") } +func (f Field) IsHandleField() bool { return strings.HasPrefix(string(f), "handle.") } +func (f Field) IsPeField() bool { + return strings.HasPrefix(string(f), "pe.") || strings.HasPrefix(string(f), "ps.pe.") || strings.HasPrefix(string(f), "ps.signature.") +} +func (f Field) IsModuleField() bool { + return strings.HasPrefix(string(f), "module.") || strings.HasPrefix(string(f), "dll.") +} +func (f Field) IsMemField() bool { return strings.HasPrefix(string(f), "mem.") } +func (f Field) IsDNSField() bool { return strings.HasPrefix(string(f), "dns.") } +func (f Field) IsThreadpoolField() bool { return strings.HasPrefix(string(f), "threadpool.") } + +func (f Field) IsPeSection() bool { return f == PeNumSections || f == PsPeNumSections } +func (f Field) IsPeSymbol() bool { + return f == PeSymbols || f == PeNumSymbols || f == PeImports || f == PsPeSymbols || f == PsPeNumSymbols || f == PsPeImports +} +func (f Field) IsPeVersionResource() bool { + return f == PeCompany || f == PeCopyright || f == PeDescription || f == PeFileName || f == PeFileVersion || f == PeProduct || f == PeProductVersion || + f == PsPeCompany || f == PsPeCopyright || f == PsPeDescription || f == PsPeFileName || f == PsPeFileVersion || f == PsPeProduct || f == PsPeProductVersion +} +func (f Field) IsPeVersionResources() bool { return f == PeResources || f == PsPeResources } +func (f Field) IsPeImphash() bool { return f == PeImphash || f == PsPeImphash } +func (f Field) IsPeDotnet() bool { return f == PeIsDotnet || f == PsPeIsDotnet } +func (f Field) IsPeAnomalies() bool { return f == PeAnomalies || f == PsPeAnomalies } +func (f Field) IsPeSignature() bool { + return f == PeIsTrusted || f == PeIsSigned || f == PeCertIssuer || f == PeCertSerial || f == PeCertSubject || f == PeCertBefore || f == PeCertAfter || strings.HasPrefix(string(f), "ps.signature.") +} +func (f Field) IsPeIsTrusted() bool { return f == PeIsTrusted || f == PsSignatureTrusted } +func (f Field) IsPeIsSigned() bool { return f == PeIsSigned || f == PsSignatureExists } + +func (f Field) IsPeCert() bool { + return strings.HasPrefix(string(f), "pe.cert.") || f == PsSignatureIssuer || f == PsSignatureSubject || f == PsSignatureSerial || f == PsSignatureAfter || f == PsSignatureBefore +} +func (f Field) IsImageCert() bool { return strings.HasPrefix(string(f), "image.cert.") } +func (f Field) IsModuleCert() bool { + return f == ModuleSignatureSubject || f == ModuleSignatureIssuer || f == ModuleSignatureSerial || f == ModuleSignatureAfter || f == ModuleSignatureBefore || + f == DllSignatureSubject || f == DllSignatureIssuer || f == DllSignatureSerial || f == DllSignatureAfter || f == DllSignatureBefore +} +func (f Field) IsModuleSignature() bool { + return strings.HasPrefix(string(f), "module.signature.") || strings.HasPrefix(string(f), "dll.signature.") +} + +func (f Field) IsPeModified() bool { return f == PeIsModified || f == PsPeIsModified } + +// Segment represents the type alias for the segment. Segment +// denotes the property anchored to the bound field reference. +// Let's look through an example. $module.name is the literal +// composed of bound field ($module) and the segment (name). +// Segments are most commonly used in the context of bound +// variables in foreach function. +type Segment string + +const ( + PathSegment Segment = "path" + NameSegment Segment = "name" + TypeSegment Segment = "type" + SizeSegment Segment = "size" + ChecksumSegment Segment = "checksum" + AddressSegment Segment = "address" + OffsetSegment Segment = "offset" + EntropySegment Segment = "entropy" + MD5Segment Segment = "md5" + + PIDSegment Segment = "pid" + CmdlineSegment Segment = "cmdline" + ExeSegment Segment = "exe" + ArgsSegment Segment = "args" + CwdSegment Segment = "cwd" + SIDSegment Segment = "sid" + SessionIDSegment Segment = "sessionid" + UsernameSegment Segment = "username" + DomainSegment Segment = "domain" + TokenIntegrityLevelSegment Segment = "token.integrity_level" + TokenIsElevatedSegment Segment = "token.is_elevated" + TokenElevationTypeSegment Segment = "token.elevation_type" + + TidSegment Segment = "tid" + StartAddressSegment Segment = "start_address" + UserStackBaseSegment Segment = "user_stack_base" + UserStackLimitSegment Segment = "user_stack_limit" + KernelStackBaseSegment Segment = "kernel_stack_base" + KernelStackLimitSegment Segment = "kernel_stack_limit" + + SymbolSegment Segment = "symbol" + ModuleSegment Segment = "module" + AllocationSizeSegment Segment = "allocation_size" + ProtectionSegment Segment = "protection" + IsUnbackedSegment Segment = "is_unbacked" + CallsiteLeadingAssemblySegment Segment = "callsite_leading_assembly" + CallsiteTrailingAssemblySegment Segment = "callsite_trailing_assembly" + + ModuleSignatureExistsSegment Segment = "module.signature.exists" + ModuleSignatureTrustedSegment Segment = "module.signature.trusted" + ModuleSignatureIssuerSegment Segment = "module.signature.issuer" + ModuleSignatureSubjectSegment Segment = "module.signature.subject" +) + +var segments = map[Segment]bool{ + NameSegment: true, + PathSegment: true, + TypeSegment: true, + EntropySegment: true, + SizeSegment: true, + MD5Segment: true, + AddressSegment: true, + ChecksumSegment: true, + PIDSegment: true, + CmdlineSegment: true, + ExeSegment: true, + ArgsSegment: true, + CwdSegment: true, + SIDSegment: true, + SessionIDSegment: true, + UsernameSegment: true, + DomainSegment: true, + TokenIntegrityLevelSegment: true, + TokenIsElevatedSegment: true, + TokenElevationTypeSegment: true, + TidSegment: true, + StartAddressSegment: true, + UserStackBaseSegment: true, + UserStackLimitSegment: true, + KernelStackBaseSegment: true, + KernelStackLimitSegment: true, + OffsetSegment: true, + SymbolSegment: true, + ModuleSegment: true, + AllocationSizeSegment: true, + ProtectionSegment: true, + IsUnbackedSegment: true, + CallsiteLeadingAssemblySegment: true, + CallsiteTrailingAssemblySegment: true, + ModuleSignatureExistsSegment: true, + ModuleSignatureTrustedSegment: true, + ModuleSignatureIssuerSegment: true, + ModuleSignatureSubjectSegment: true, +} + +var allowedSegments = map[Field][]Segment{ + PsAncestors: {NameSegment, PIDSegment, CmdlineSegment, ExeSegment, ArgsSegment, CwdSegment, SIDSegment, SessionIDSegment, UsernameSegment, DomainSegment, TokenIntegrityLevelSegment, TokenIsElevatedSegment, TokenElevationTypeSegment}, + PsThreads: {TidSegment, StartAddressSegment, UserStackBaseSegment, UserStackLimitSegment, KernelStackBaseSegment, KernelStackLimitSegment}, + PsModules: {PathSegment, NameSegment, AddressSegment, SizeSegment, ChecksumSegment}, + PsMmaps: {AddressSegment, TypeSegment, SizeSegment, ProtectionSegment, PathSegment}, + PeSections: {NameSegment, SizeSegment, EntropySegment, MD5Segment}, + PsPeSections: {NameSegment, SizeSegment, EntropySegment, MD5Segment}, + ThreadCallstack: {AddressSegment, OffsetSegment, SymbolSegment, ModuleSegment, AllocationSizeSegment, ProtectionSegment, IsUnbackedSegment, CallsiteLeadingAssemblySegment, CallsiteTrailingAssemblySegment, ModuleSignatureExistsSegment, ModuleSignatureTrustedSegment, ModuleSignatureIssuerSegment, ModuleSignatureSubjectSegment}, +} + +func (s Segment) IsEntropy() bool { return s == EntropySegment } + +// IsSegmentAllowed determines if the segment is valid for the pseudo field. +func IsSegmentAllowed(f Field, s Segment) bool { + segs := allowedSegments[f] + if len(segs) == 0 { + return false + } + + for _, seg := range segs { + if seg == s { + return true + } + } + + return false +} + +// SegmentsHint returns the sequence of available segments for the pseudo field. +func SegmentsHint(f Field) string { + segs := allowedSegments[f] + if len(segs) == 0 { + return "" + } + + s := make([]string, len(segs)) + for i, seg := range segs { + s[i] = string(seg) + } + + return strings.Join(s, ", ") +} + +// IsSegment indicates if the given string is recognized as a known segment. +func IsSegment(s string) bool { + return segments[Segment(s)] +} + +// Pseudo fields provide access to the process/event internal state. They +// are typically used in conjunction with the foreach function as its +// first argument. + +var ( + PsModules Field = "ps._modules" + PsThreads Field = "ps._threads" + PsMmaps Field = "ps._mmaps" + PsAncestors Field = "ps._ancestors" + PsPeSections Field = "ps.pe._sections" + ThreadCallstack Field = "thread._callstack" + PeSections Field = "pe._sections" +) + +func IsPseudoField(f Field) bool { + return f == PsAncestors || f == PsModules || f == PsThreads || f == PsMmaps || f == ThreadCallstack || f == PeSections || f == PsPeSections +} + +func (f Field) IsPeSectionsPseudo() bool { return f == PeSections || f == PsPeSections } + +var fields = map[Field]FieldInfo{ + EvtSeq: {EvtSeq, "event sequence number", params.Uint64, []string{"evt.seq > 666"}, nil, nil}, + EvtPID: {EvtPID, "process identifier generating the event", params.Uint32, []string{"evt.pid = 6"}, nil, nil}, + EvtTID: {EvtTID, "thread identifier generating the event", params.Uint32, []string{"evt.tid = 1024"}, nil, nil}, + EvtCPU: {EvtCPU, "logical processor core where the event was generated", params.Uint8, []string{"evt.cpu = 2"}, nil, nil}, + EvtName: {EvtName, "symbolical event name", params.AnsiString, []string{"evt.name = 'CreateThread'"}, nil, nil}, + EvtCategory: {EvtCategory, "event category", params.AnsiString, []string{"evt.category = 'registry'"}, nil, nil}, + EvtDesc: {EvtDesc, "event description", params.AnsiString, []string{"evt.desc contains 'Creates a new process'"}, nil, nil}, + EvtHost: {EvtHost, "host name on which the event was produced", params.UnicodeString, []string{"evt.host contains 'kitty'"}, nil, nil}, + EvtTime: {EvtTime, "event timestamp as a time string", params.Time, []string{"evt.time = '17:05:32'"}, nil, nil}, + EvtTimeHour: {EvtTimeHour, "hour within the day on which the event occurred", params.Time, []string{"evt.time.h = 23"}, nil, nil}, + EvtTimeMin: {EvtTimeMin, "minute offset within the hour on which the event occurred", params.Time, []string{"evt.time.m = 54"}, nil, nil}, + EvtTimeSec: {EvtTimeSec, "second offset within the minute on which the event occurred", params.Time, []string{"evt.time.s = 0"}, nil, nil}, + EvtTimeNs: {EvtTimeNs, "nanoseconds specified by event timestamp", params.Int64, []string{"evt.time.ns > 1591191629102337000"}, nil, nil}, + EvtDate: {EvtDate, "event timestamp as a date string", params.Time, []string{"evt.date = '2018-03-03'"}, nil, nil}, + EvtDateDay: {EvtDateDay, "day of the month on which the event occurred", params.Time, []string{"evt.date.d = 12"}, nil, nil}, + EvtDateMonth: {EvtDateMonth, "month of the year on which the event occurred", params.Time, []string{"evt.date.m = 11"}, nil, nil}, + EvtDateYear: {EvtDateYear, "year on which the event occurred", params.Uint32, []string{"evt.date.y = 2020"}, nil, nil}, + EvtDateTz: {EvtDateTz, "time zone associated with the event timestamp", params.AnsiString, []string{"evt.date.tz = 'UTC'"}, nil, nil}, + EvtDateWeek: {EvtDateWeek, "week number within the year on which the event occurred", params.Uint8, []string{"evt.date.week = 2"}, nil, nil}, + EvtDateWeekday: {EvtDateWeekday, "week day on which the event occurred", params.AnsiString, []string{"evt.date.weekday = 'Monday'"}, nil, nil}, + EvtNparams: {EvtNparams, "number of parameters", params.Int8, []string{"evt.nparams > 2"}, nil, nil}, + EvtArg: {EvtArg, "event parameter", params.Object, []string{"evt.arg[cmdline] istartswith 'C:\\Windows'"}, nil, &Argument{Optional: false, Pattern: "[a-z0-9_]+", ValidationFunc: func(s string) bool { + for _, c := range s { + switch { + case unicode.IsLower(c): + case unicode.IsNumber(c): + case c == '_': + default: + return false + } + } + return true + }}}, + EvtIsDirectSyscall: {EvtIsDirectSyscall, "indicates if the event is performing a direct syscall", params.Bool, []string{"evt.is_direct_syscall = true"}, nil, nil}, + EvtIsIndirectSyscall: {EvtIsIndirectSyscall, "indicates if the event is performing an indirect syscall", params.Bool, []string{"evt.is_indirect_syscall = true"}, nil, nil}, + + KevtSeq: {KevtSeq, "event sequence number", params.Uint64, []string{"kevt.seq > 666"}, &Deprecation{Since: "3.0.0", Fields: []Field{EvtSeq}}, nil}, + KevtPID: {KevtPID, "process identifier generating the event", params.Uint32, []string{"kevt.pid = 6"}, &Deprecation{Since: "3.0.0", Fields: []Field{EvtPID}}, nil}, + KevtTID: {KevtTID, "thread identifier generating the event", params.Uint32, []string{"kevt.tid = 1024"}, &Deprecation{Since: "3.0.0", Fields: []Field{EvtTID}}, nil}, + KevtCPU: {KevtCPU, "logical processor core where the event was generated", params.Uint8, []string{"kevt.cpu = 2"}, &Deprecation{Since: "3.0.0", Fields: []Field{EvtCPU}}, nil}, + KevtName: {KevtName, "symbolical event name", params.AnsiString, []string{"kevt.name = 'CreateThread'"}, &Deprecation{Since: "3.0.0", Fields: []Field{EvtName}}, nil}, + KevtCategory: {KevtCategory, "event category", params.AnsiString, []string{"kevt.category = 'registry'"}, &Deprecation{Since: "3.0.0", Fields: []Field{EvtCategory}}, nil}, + KevtDesc: {KevtDesc, "event description", params.AnsiString, []string{"kevt.desc contains 'Creates a new process'"}, &Deprecation{Since: "3.0.0", Fields: []Field{EvtDesc}}, nil}, + KevtHost: {KevtHost, "host name on which the event was produced", params.UnicodeString, []string{"kevt.host contains 'kitty'"}, &Deprecation{Since: "3.0.0", Fields: []Field{EvtHost}}, nil}, + KevtTime: {KevtTime, "event timestamp as a time string", params.Time, []string{"kevt.time = '17:05:32'"}, &Deprecation{Since: "3.0.0", Fields: []Field{EvtTime}}, nil}, + KevtTimeHour: {KevtTimeHour, "hour within the day on which the event occurred", params.Time, []string{"kevt.time.h = 23"}, &Deprecation{Since: "3.0.0", Fields: []Field{EvtTimeHour}}, nil}, + KevtTimeMin: {KevtTimeMin, "minute offset within the hour on which the event occurred", params.Time, []string{"kevt.time.m = 54"}, &Deprecation{Since: "3.0.0", Fields: []Field{EvtTimeMin}}, nil}, + KevtTimeSec: {KevtTimeSec, "second offset within the minute on which the event occurred", params.Time, []string{"kevt.time.s = 0"}, &Deprecation{Since: "3.0.0", Fields: []Field{EvtTimeSec}}, nil}, + KevtTimeNs: {KevtTimeNs, "nanoseconds specified by event timestamp", params.Int64, []string{"kevt.time.ns > 1591191629102337000"}, &Deprecation{Since: "3.0.0", Fields: []Field{EvtTimeNs}}, nil}, + KevtDate: {KevtDate, "event timestamp as a date string", params.Time, []string{"kevt.date = '2018-03-03'"}, &Deprecation{Since: "3.0.0", Fields: []Field{EvtDate}}, nil}, + KevtDateDay: {KevtDateDay, "day of the month on which the event occurred", params.Time, []string{"kevt.date.d = 12"}, &Deprecation{Since: "3.0.0", Fields: []Field{EvtDateDay}}, nil}, + KevtDateMonth: {KevtDateMonth, "month of the year on which the event occurred", params.Time, []string{"kevt.date.m = 11"}, &Deprecation{Since: "3.0.0", Fields: []Field{EvtDateMonth}}, nil}, + KevtDateYear: {KevtDateYear, "year on which the event occurred", params.Uint32, []string{"kevt.date.y = 2020"}, &Deprecation{Since: "3.0.0", Fields: []Field{EvtDateYear}}, nil}, + KevtDateTz: {KevtDateTz, "time zone associated with the event timestamp", params.AnsiString, []string{"kevt.date.tz = 'UTC'"}, &Deprecation{Since: "3.0.0", Fields: []Field{EvtDateTz}}, nil}, + KevtDateWeek: {KevtDateWeek, "week number within the year on which the event occurred", params.Uint8, []string{"kevt.date.week = 2"}, &Deprecation{Since: "3.0.0", Fields: []Field{EvtDateWeek}}, nil}, + KevtDateWeekday: {KevtDateWeekday, "week day on which the event occurred", params.AnsiString, []string{"kevt.date.weekday = 'Monday'"}, &Deprecation{Since: "3.0.0", Fields: []Field{EvtDateWeekday}}, nil}, + KevtNparams: {KevtNparams, "number of parameters", params.Int8, []string{"kevt.nparams > 2"}, &Deprecation{Since: "3.0.0", Fields: []Field{EvtNparams}}, nil}, + KevtArg: {KevtArg, "event parameter", params.Object, []string{"kevt.arg[cmdline] istartswith 'C:\\Windows'"}, &Deprecation{Since: "3.0.0", Fields: []Field{EvtArg}}, &Argument{Optional: false, Pattern: "[a-z0-9_]+", ValidationFunc: func(s string) bool { + for _, c := range s { + switch { + case unicode.IsLower(c): + case unicode.IsNumber(c): + case c == '_': + default: + return false + } + } + return true + }}}, + + PsPid: {PsPid, "process identifier", params.PID, []string{"ps.pid = 1024"}, nil, nil}, + PsPpid: {PsPpid, "parent process identifier", params.PID, []string{"ps.ppid = 45"}, nil, nil}, + PsName: {PsName, "process image name including the file extension", params.UnicodeString, []string{"ps.name contains 'firefox'"}, nil, nil}, + PsComm: {PsComm, "process command line", params.UnicodeString, []string{"ps.comm contains 'java'"}, &Deprecation{Since: "1.10.0", Fields: []Field{PsCmdline}}, nil}, + PsCmdline: {PsCmdline, "process command line", params.UnicodeString, []string{"ps.cmdline contains 'java'"}, nil, nil}, + PsExe: {PsExe, "full name of the process' executable", params.UnicodeString, []string{"ps.exe = 'C:\\Windows\\system32\\cmd.exe'"}, nil, nil}, + PsArgs: {PsArgs, "process command line arguments", params.Slice, []string{"ps.args in ('/cdir', '/-C')"}, nil, nil}, + PsCwd: {PsCwd, "process current working directory", params.UnicodeString, []string{"ps.cwd = 'C:\\Users\\Default'"}, nil, nil}, + PsSID: {PsSID, "security identifier under which this process is run", params.UnicodeString, []string{"ps.sid contains 'SYSTEM'"}, nil, nil}, + PsSessionID: {PsSessionID, "unique identifier for the current session", params.Int16, []string{"ps.sessionid = 1"}, nil, nil}, + PsDomain: {PsDomain, "process domain", params.UnicodeString, []string{"ps.domain contains 'SERVICE'"}, nil, nil}, + PsUsername: {PsUsername, "process username", params.UnicodeString, []string{"ps.username contains 'system'"}, nil, nil}, + PsEnvs: {PsEnvs, "process environment variables", params.Slice, []string{"ps.envs in ('SystemRoot:C:\\WINDOWS')", "ps.envs[windir] = 'C:\\WINDOWS'"}, nil, &Argument{Optional: true, ValidationFunc: func(arg string) bool { return true }}}, + PsHandleNames: {PsHandleNames, "allocated process handle names", params.Slice, []string{"ps.handles in ('\\BaseNamedObjects\\__ComCatalogCache__')"}, nil, nil}, + PsHandleTypes: {PsHandleTypes, "allocated process handle types", params.Slice, []string{"ps.handle.types in ('Key', 'Mutant', 'Section')"}, nil, nil}, + PsDTB: {PsDTB, "process directory table base address", params.Address, []string{"ps.dtb = '7ffe0000'"}, nil, nil}, + PsModuleNames: {PsModuleNames, "modules loaded by the process", params.Slice, []string{"ps.modules in ('crypt32.dll', 'xul.dll')"}, nil, nil}, + PsParentName: {PsParentName, "parent process image name including the file extension", params.UnicodeString, []string{"ps.parent.name contains 'cmd.exe'"}, nil, nil}, + PsParentPid: {PsParentPid, "parent process id", params.Uint32, []string{"ps.parent.pid = 4"}, nil, nil}, + PsParentComm: {PsParentComm, "parent process command line", params.UnicodeString, []string{"ps.parent.comm contains 'java'"}, &Deprecation{Since: "1.10.0", Fields: []Field{PsParentCmdline}}, nil}, + PsParentCmdline: {PsParentCmdline, "parent process command line", params.UnicodeString, []string{"ps.parent.cmdline contains 'java'"}, nil, nil}, + PsParentExe: {PsParentExe, "full name of the parent process' executable", params.UnicodeString, []string{"ps.parent.exe = 'C:\\Windows\\system32\\explorer.exe'"}, nil, nil}, + PsParentArgs: {PsParentArgs, "parent process command line arguments", params.Slice, []string{"ps.parent.args in ('/cdir', '/-C')"}, nil, nil}, + PsParentCwd: {PsParentCwd, "parent process current working directory", params.UnicodeString, []string{"ps.parent.cwd = 'C:\\Temp'"}, nil, nil}, + PsParentSID: {PsParentSID, "security identifier under which the parent process is run", params.UnicodeString, []string{"ps.parent.sid contains 'SYSTEM'"}, nil, nil}, + PsParentDomain: {PsParentDomain, "parent process domain", params.UnicodeString, []string{"ps.parent.domain contains 'SERVICE'"}, nil, nil}, + PsParentUsername: {PsParentUsername, "parent process username", params.UnicodeString, []string{"ps.parent.username contains 'system'"}, nil, nil}, + PsParentSessionID: {PsParentSessionID, "unique identifier for the current session of parent process", params.Int16, []string{"ps.parent.sessionid = 1"}, nil, nil}, + PsParentEnvs: {PsParentEnvs, "parent process environment variables", params.Slice, []string{"ps.parent.envs in ('MOZ_CRASHREPORTER_DATA_DIRECTORY')"}, nil, nil}, + PsParentHandles: {PsParentHandles, "allocated parent process handle names", params.Slice, []string{"ps.parent.handles in ('\\BaseNamedObjects\\__ComCatalogCache__')"}, nil, nil}, + PsParentHandleTypes: {PsParentHandleTypes, "allocated parent process handle types", params.Slice, []string{"ps.parent.handle.types in ('File', 'SymbolicLink')"}, nil, nil}, + PsParentDTB: {PsParentDTB, "parent process directory table base address", params.Address, []string{"ps.parent.dtb = '7ffe0000'"}, nil, nil}, + PsAccessMask: {PsAccessMask, "process desired access rights", params.AnsiString, []string{"ps.access.mask = '0x1400'"}, nil, nil}, + PsAccessMaskNames: {PsAccessMaskNames, "process desired access rights as a string list", params.Slice, []string{"ps.access.mask.names in ('SUSPEND_RESUME')"}, nil, nil}, + PsAccessStatus: {PsAccessStatus, "process access status", params.UnicodeString, []string{"ps.access.status = 'access is denied.'"}, nil, nil}, + PsUUID: {PsUUID, "unique process identifier", params.Uint64, []string{"ps.uuid > 6000054355"}, nil, nil}, + PsParentUUID: {PsParentUUID, "unique parent process identifier", params.Uint64, []string{"ps.parent.uuid > 6000054355"}, nil, nil}, + PsIsWOW64Field: {PsIsWOW64Field, "indicates if the process generating the event is a 32-bit process created in 64-bit Windows system", params.Bool, []string{"ps.is_wow64"}, nil, nil}, + PsIsPackagedField: {PsIsPackagedField, "indicates if the process generating the event is packaged with the MSIX technology", params.Bool, []string{"ps.is_packaged"}, nil, nil}, + PsIsProtectedField: {PsIsProtectedField, "indicates if the process generating the event is a protected process", params.Bool, []string{"ps.is_protected"}, nil, nil}, + PsParentIsWOW64Field: {PsParentIsWOW64Field, "indicates if the parent process generating the event is a 32-bit process created in 64-bit Windows system", params.Bool, []string{"ps.parent.is_wow64"}, nil, nil}, + PsParentIsPackagedField: {PsParentIsPackagedField, "indicates if the parent process generating the event is packaged with the MSIX technology", params.Bool, []string{"ps.parent.is_packaged"}, nil, nil}, + PsParentIsProtectedField: {PsParentIsProtectedField, "indicates if the the parent process generating the event is a protected process", params.Bool, []string{"ps.parent.is_protected"}, nil, nil}, + PsAncestor: {PsAncestor, "the process ancestor name", params.UnicodeString, []string{"ps.ancestor[1] = 'svchost.exe'", "ps.ancestor in ('winword.exe')"}, nil, &Argument{Optional: true, Pattern: "[0-9]+", ValidationFunc: isNumber}}, + PsTokenIntegrityLevel: {PsTokenIntegrityLevel, "process token integrity level", params.UnicodeString, []string{"ps.token.integrity_level = 'SYSTEM'"}, nil, nil}, + PsTokenIsElevated: {PsTokenIsElevated, "indicates if the process token is elevated", params.Bool, []string{"ps.token.is_elevated = true"}, nil, nil}, + PsTokenElevationType: {PsTokenElevationType, "process token elevation type", params.AnsiString, []string{"ps.token.elevation_type = 'LIMITED'"}, nil, nil}, + PsParentTokenIntegrityLevel: {PsParentTokenIntegrityLevel, "parent process token integrity level", params.UnicodeString, []string{"ps.parent.token.integrity_level = 'HIGH'"}, nil, nil}, + PsParentTokenIsElevated: {PsParentTokenIsElevated, "indicates if the parent process token is elevated", params.Bool, []string{"ps.parent.token.is_elevated = true"}, nil, nil}, + PsParentTokenElevationType: {PsParentTokenElevationType, "parent process token elevation type", params.AnsiString, []string{"ps.parent.token.elevation_type = 'LIMITED'"}, nil, nil}, + PsSignatureExists: {PsSignatureExists, "indicates if the process executable has a valid signature", params.Bool, []string{"ps.signature.exists"}, nil, nil}, + PsSignatureTrusted: {PsSignatureTrusted, "indicates if the process executable signature certificate chain is trusted", params.Bool, []string{"ps.signature.trusted"}, nil, nil}, + PsSignatureSerial: {PsSignatureSerial, "represents signature serial number", params.UnicodeString, []string{"ps.signature.serial = '330000023241fb59996dcc4dff000000000232'"}, nil, nil}, + PsSignatureSubject: {PsSignatureSubject, "represents signature subject", params.UnicodeString, []string{"ps.signature.subject contains 'Washington, Redmond, Microsoft Corporation'"}, nil, nil}, + PsSignatureIssuer: {PsSignatureIssuer, "represents signature CA", params.UnicodeString, []string{"ps.signature.issuer contains 'Washington, Redmond, Microsoft Corporation'"}, nil, nil}, + PsSignatureAfter: {PsSignatureAfter, "represents certificate expiration date", params.Time, []string{"ps.signature.after contains '2024-02-01 00:05:42 +0000 UTC'"}, nil, nil}, + PsSignatureBefore: {PsSignatureBefore, "represents certificate enrollment date", params.Time, []string{"ps.signature.before contains '2024-02-01 00:05:42 +0000 UTC'"}, nil, nil}, + + PsPeNumSections: {PsPeNumSections, "number of PE sections", params.Uint16, []string{"ps.pe.nsections < 5"}, nil, nil}, + PsPeNumSymbols: {PsPeNumSymbols, "number of entries in the symbol table", params.Uint32, []string{"ps.pe.nsymbols > 230"}, nil, nil}, + PsPeBaseAddress: {PsPeBaseAddress, "executable base address", params.Address, []string{"ps.pe.address.base = '140000000'"}, nil, nil}, + PsPeEntrypoint: {PsPeEntrypoint, "address of the entrypoint function", params.Address, []string{"ps.pe.address.entrypoint = '20110'"}, nil, nil}, + PsPeSymbols: {PsPeSymbols, "imported symbols", params.Slice, []string{"ps.pe.symbols in ('GetTextFaceW', 'GetProcessHeap')"}, nil, nil}, + PsPeImports: {PsPeImports, "imported dynamic linked libraries", params.Slice, []string{"ps.pe.imports in ('msvcrt.dll', 'GDI32.dll'"}, nil, nil}, + PsPeResources: {PsPeResources, "version resources", params.Map, []string{"ps.pe.resources[FileDescription] = 'Notepad'"}, nil, &Argument{Optional: true, Pattern: "[a-zA-Z0-9_]+", ValidationFunc: func(s string) bool { + for _, c := range s { + switch { + case unicode.IsLower(c): + case unicode.IsUpper(c): + case unicode.IsNumber(c): + case c == '_': + default: + return false + } + } + return true + }}}, + PsPeCompany: {PsPeCompany, "internal company name of the file provided at compile-time", params.UnicodeString, []string{"ps.pe.company = 'Microsoft Corporation'"}, nil, nil}, + PsPeCopyright: {PsPeCopyright, "copyright notice for the file emitted at compile-time", params.UnicodeString, []string{"ps.pe.copyright = '© Microsoft Corporation'"}, nil, nil}, + PsPeDescription: {PsPeDescription, "internal description of the file provided at compile-time", params.UnicodeString, []string{"ps.pe.description = 'Notepad'"}, nil, nil}, + PsPeFileName: {PsPeFileName, "original file name supplied at compile-time", params.UnicodeString, []string{"ps.pe.file.name = 'NOTEPAD.EXE'"}, nil, nil}, + PsPeFileVersion: {PsPeFileVersion, "file version supplied at compile-time", params.UnicodeString, []string{"ps.pe.file.version = '10.0.18362.693 (WinBuild.160101.0800)'"}, nil, nil}, + PsPeProduct: {PsPeProduct, "internal product name of the file provided at compile-time", params.UnicodeString, []string{"ps.pe.product = 'Microsoft® Windows® Operating System'"}, nil, nil}, + PsPeProductVersion: {PsPeProductVersion, "internal product version of the file provided at compile-time", params.UnicodeString, []string{"ps.pe.product.version = '10.0.18362.693'"}, nil, nil}, + PsPeImphash: {PsPeImphash, "import hash", params.AnsiString, []string{"pe.impash = '5d3861c5c547f8a34e471ba273a732b2'"}, nil, nil}, + PsPeIsDotnet: {PsPeIsDotnet, "indicates if PE contains CLR data", params.Bool, []string{"ps.pe.is_dotnet"}, nil, nil}, + PsPeAnomalies: {PsPeAnomalies, "contains PE anomalies detected during parsing", params.Slice, []string{"ps.pe.anomalies in ('number of sections is 0')"}, nil, nil}, + PsPeIsModified: {PsPeIsModified, "indicates if disk and in-memory PE headers differ", params.Bool, []string{"ps.pe.is_modified"}, nil, nil}, + + ThreadBasePrio: {ThreadBasePrio, "scheduler priority of the thread", params.Int8, []string{"thread.prio = 5"}, nil, nil}, + ThreadIOPrio: {ThreadIOPrio, "I/O priority hint for scheduling I/O operations", params.Int8, []string{"thread.io.prio = 4"}, nil, nil}, + ThreadPagePrio: {ThreadPagePrio, "memory page priority hint for memory pages accessed by the thread", params.Int8, []string{"thread.page.prio = 12"}, nil, nil}, + ThreadKstackBase: {ThreadKstackBase, "base address of the thread's kernel space stack", params.Address, []string{"thread.kstack.base = 'a65d800000'"}, nil, nil}, + ThreadKstackLimit: {ThreadKstackLimit, "limit of the thread's kernel space stack", params.Address, []string{"thread.kstack.limit = 'a85d800000'"}, nil, nil}, + ThreadUstackBase: {ThreadUstackBase, "base address of the thread's user space stack", params.Address, []string{"thread.ustack.base = '7ffe0000'"}, nil, nil}, + ThreadUstackLimit: {ThreadUstackLimit, "limit of the thread's user space stack", params.Address, []string{"thread.ustack.limit = '8ffe0000'"}, nil, nil}, + ThreadEntrypoint: {ThreadEntrypoint, "starting address of the function to be executed by the thread", params.Address, []string{"thread.entrypoint = '7efe0000'"}, &Deprecation{Since: "2.3.0", Fields: []Field{ThreadStartAddress}}, nil}, + ThreadStartAddress: {ThreadStartAddress, "thread start address", params.Address, []string{"thread.start_address = '7efe0000'"}, nil, nil}, + ThreadStartAddressSymbol: {ThreadStartAddressSymbol, "thread start address symbol", params.UnicodeString, []string{"thread.start_address.symbol = 'LoadModule'"}, nil, nil}, + ThreadStartAddressModule: {ThreadStartAddressModule, "thread start address module", params.UnicodeString, []string{"thread.start_address.module endswith 'kernel32.dll'"}, nil, nil}, + ThreadPID: {ThreadPID, "the process identifier where the thread is created", params.Uint32, []string{"evt.pid != thread.pid"}, nil, nil}, + ThreadTEB: {ThreadTEB, "the base address of the thread environment block", params.Address, []string{"thread.teb_address = '8f30893000'"}, nil, nil}, + ThreadAccessMask: {ThreadAccessMask, "thread desired access rights", params.AnsiString, []string{"thread.access.mask = '0x1fffff'"}, nil, nil}, + ThreadAccessMaskNames: {ThreadAccessMaskNames, "thread desired access rights as a string list", params.Slice, []string{"thread.access.mask.names in ('IMPERSONATE')"}, nil, nil}, + ThreadAccessStatus: {ThreadAccessStatus, "thread access status", params.UnicodeString, []string{"thread.access.status = 'success'"}, nil, nil}, + ThreadCallstackSummary: {ThreadCallstackSummary, "callstack summary", params.UnicodeString, []string{"thread.callstack.summary contains 'ntdll.dll|KERNELBASE.dll'"}, nil, nil}, + ThreadCallstackKernelSummary: {ThreadCallstackKernelSummary, "kernel thread callstack summary", params.UnicodeString, []string{"thread.callstack.kernel_summary contains 'fileinfo.sys|ntoskrnl.exe|FLTMGR.SYS|ntoskrnl.exe'"}, nil, nil}, + ThreadCallstackDetail: {ThreadCallstackDetail, "detailed information of each stack frame", params.UnicodeString, []string{"thread.callstack.detail contains 'KERNELBASE.dll!CreateProcessW'"}, nil, nil}, + ThreadCallstackModules: {ThreadCallstackModules, "list of modules comprising the callstack", params.Slice, []string{"thread.callstack.modules in ('C:\\WINDOWS\\System32\\KERNELBASE.dll')", "base(thread.callstack.modules[7]) = 'ntdll.dll'"}, nil, &Argument{Optional: true, Pattern: "[0-9]+", ValidationFunc: isNumber}}, + ThreadCallstackSymbols: {ThreadCallstackSymbols, "list of symbols comprising the callstack", params.Slice, []string{"thread.callstack.symbols in ('ntdll.dll!NtCreateProcess')", "thread.callstack.symbols[3] = 'ntdll!NtCreateProcess'"}, nil, &Argument{Optional: true, Pattern: "[0-9]+", ValidationFunc: isNumber}}, + ThreadCallstackAllocationSizes: {ThreadCallstackAllocationSizes, "allocation sizes of private pages", params.Slice, []string{"thread.callstack.allocation_sizes > 10000"}, nil, nil}, + ThreadCallstackProtections: {ThreadCallstackProtections, "page protections masks of each frame", params.Slice, []string{"thread.callstack.protections in ('RWX', 'WX')"}, nil, nil}, + ThreadCallstackCallsiteLeadingAssembly: {ThreadCallstackCallsiteLeadingAssembly, "callsite leading assembly instructions", params.Slice, []string{"thread.callstack.callsite_leading_assembly in ('mov r10,rcx', 'syscall')"}, nil, nil}, + ThreadCallstackCallsiteTrailingAssembly: {ThreadCallstackCallsiteTrailingAssembly, "callsite trailing assembly instructions", params.Slice, []string{"thread.callstack.callsite_trailing_assembly in ('add esp, 0xab')"}, nil, nil}, + ThreadCallstackIsUnbacked: {ThreadCallstackIsUnbacked, "indicates if the callstack contains unbacked regions", params.Bool, []string{"thread.callstack.is_unbacked"}, nil, nil}, + ThreadCallstackAddresses: {ThreadCallstackAddresses, "list of all stack return addresses", params.Slice, []string{"thread.callstack.addresses in ('7ffb5c1d0396')"}, nil, nil}, + ThreadCallstackFinalUserModuleName: {ThreadCallstackFinalUserModuleName, "final user space stack frame module name", params.UnicodeString, []string{"thread.callstack.final_user_module.name != 'ntdll.dll'"}, nil, nil}, + ThreadCallstackFinalUserModulePath: {ThreadCallstackFinalUserModulePath, "final user space stack frame module path", params.UnicodeString, []string{"thread.callstack.final_user_module.path imatches '?:\\Windows\\System32\\ntdll.dll'"}, nil, nil}, + ThreadCallstackFinalUserSymbolName: {ThreadCallstackFinalUserSymbolName, "final user space stack symbol name", params.UnicodeString, []string{"thread.callstack.final_user_symbol.name imatches 'CreateProcess*'"}, nil, nil}, + ThreadCallstackFinalKernelModuleName: {ThreadCallstackFinalKernelModuleName, "final kernel space stack frame module name", params.UnicodeString, []string{"thread.callstack.final_kernel_module.name = 'FLTMGR.SYS'"}, nil, nil}, + ThreadCallstackFinalKernelModulePath: {ThreadCallstackFinalKernelModulePath, "final kernel space stack frame module path", params.UnicodeString, []string{"thread.callstack.final_kernel_module.path imatches '?:\\WINDOWS\\System32\\drivers\\FLTMGR.SYS'"}, nil, nil}, + ThreadCallstackFinalKernelSymbolName: {ThreadCallstackFinalKernelSymbolName, "final kernel space stack symbol name", params.UnicodeString, []string{"thread.callstack.final_kernel_symbol.name = 'FltGetStreamContext'"}, nil, nil}, + ThreadCallstackFinalUserModuleSignatureExists: {ThreadCallstackFinalUserModuleSignatureExists, "signature status of the final user space stack frame module", params.Bool, []string{"thread.callstack.final_user_module.signature.exists = true"}, nil, nil}, + ThreadCallstackFinalUserModuleSignatureTrusted: {ThreadCallstackFinalUserModuleSignatureTrusted, "signature trust status of the final user space stack frame module", params.Bool, []string{"thread.callstack.final_user_module.signature.trusted = true"}, nil, nil}, + ThreadCallstackFinalUserModuleSignatureIssuer: {ThreadCallstackFinalUserModuleSignatureIssuer, "final user space stack frame module signature certificate issuer", params.UnicodeString, []string{"thread.callstack.final_user_module.signature.issuer imatches '*Microsoft Corporation*'"}, nil, nil}, + ThreadCallstackFinalUserModuleSignatureSubject: {ThreadCallstackFinalUserModuleSignatureSubject, "final user space stack frame module signature certificate subject", params.UnicodeString, []string{"thread.callstack.final_user_module.signature.subject imatches '*Microsoft Windows*'"}, nil, nil}, + + ImagePath: {ImagePath, "full image path", params.UnicodeString, []string{"image.path = 'C:\\Windows\\System32\\advapi32.dll'"}, &Deprecation{Since: "3.0.0", Fields: []Field{ModulePath}}, nil}, + ImageName: {ImageName, "image name", params.UnicodeString, []string{"image.name = 'advapi32.dll'"}, &Deprecation{Since: "3.0.0", Fields: []Field{ModuleName}}, nil}, + ImageBase: {ImageBase, "the base address of process in which the image is loaded", params.Address, []string{"image.base.address = 'a65d800000'"}, &Deprecation{Since: "3.0.0", Fields: []Field{ModuleBase}}, nil}, + ImageChecksum: {ImageChecksum, "image checksum", params.Uint32, []string{"image.checksum = 746424"}, &Deprecation{Since: "3.0.0", Fields: []Field{ModuleChecksum}}, nil}, + ImageSize: {ImageSize, "image size", params.Uint32, []string{"image.size > 1024"}, &Deprecation{Since: "3.0.0", Fields: []Field{ModuleSize}}, nil}, + ImageDefaultAddress: {ImageDefaultAddress, "default image address", params.Address, []string{"image.default.address = '7efe0000'"}, &Deprecation{Since: "3.0.0", Fields: []Field{ModuleDefaultAddress}}, nil}, + ImagePID: {ImagePID, "target process identifier", params.Uint32, []string{"image.pid = 80"}, &Deprecation{Since: "3.0.0", Fields: []Field{ModulePID}}, nil}, + ImageSignatureType: {ImageSignatureType, "image signature type", params.AnsiString, []string{"image.signature.type != 'NONE'"}, &Deprecation{Since: "3.0.0", Fields: []Field{ModuleSignatureType}}, nil}, + ImageSignatureLevel: {ImageSignatureLevel, "image signature level", params.AnsiString, []string{"image.signature.level = 'AUTHENTICODE'"}, &Deprecation{Since: "3.0.0", Fields: []Field{ModuleSignatureLevel}}, nil}, + ImageCertSerial: {ImageCertSerial, "image certificate serial number", params.UnicodeString, []string{"image.cert.serial = '330000023241fb59996dcc4dff000000000232'"}, &Deprecation{Since: "3.0.0", Fields: []Field{ModuleSignatureSerial}}, nil}, + ImageCertSubject: {ImageCertSubject, "image certificate subject", params.UnicodeString, []string{"image.cert.subject contains 'Washington, Redmond, Microsoft Corporation'"}, &Deprecation{Since: "3.0.0", Fields: []Field{ModuleSignatureSubject}}, nil}, + ImageCertIssuer: {ImageCertIssuer, "image certificate CA", params.UnicodeString, []string{"image.cert.issuer contains 'Washington, Redmond, Microsoft Corporation'"}, &Deprecation{Since: "3.0.0", Fields: []Field{ModuleSignatureIssuer}}, nil}, + ImageCertAfter: {ImageCertAfter, "image certificate expiration date", params.Time, []string{"image.cert.after contains '2024-02-01 00:05:42 +0000 UTC'"}, &Deprecation{Since: "3.0.0", Fields: []Field{ModuleSignatureAfter}}, nil}, + ImageCertBefore: {ImageCertBefore, "image certificate enrollment date", params.Time, []string{"image.cert.before contains '2024-02-01 00:05:42 +0000 UTC'"}, &Deprecation{Since: "3.0.0", Fields: []Field{ModuleSignatureBefore}}, nil}, + ImageIsDLL: {ImageIsDLL, "indicates if the loaded image is a DLL", params.Bool, []string{"image.is_dll'"}, &Deprecation{Since: "3.0.0", Fields: []Field{ModuleIsDLL}}, nil}, + ImageIsDriver: {ImageIsDriver, "indicates if the loaded image is a driver", params.Bool, []string{"image.is_driver'"}, &Deprecation{Since: "3.0.0", Fields: []Field{ModuleIsDriver}}, nil}, + ImageIsExecutable: {ImageIsExecutable, "indicates if the loaded image is an executable", params.Bool, []string{"image.is_exec'"}, &Deprecation{Since: "3.0.0", Fields: []Field{ModuleIsExecutable}}, nil}, + ImageIsDotnet: {ImageIsDotnet, "indicates if the loaded image is a .NET assembly", params.Bool, []string{"image.is_dotnet'"}, &Deprecation{Since: "3.0.0", Fields: []Field{ModuleIsDotnet}}, nil}, + ModulePath: {ModulePath, "full module path", params.UnicodeString, []string{"module.path = 'C:\\Windows\\System32\\advapi32.dll'"}, nil, nil}, + ModulePathStem: {ModulePathStem, "module path stem", params.UnicodeString, []string{"module.path.stem = 'C:\\Windows\\System32\\advapi32'"}, nil, nil}, + ModuleName: {ModuleName, "module name", params.UnicodeString, []string{"module.name = 'advapi32.dll'"}, nil, nil}, + ModuleBase: {ModuleBase, "the base address of process in which the module is loaded", params.Address, []string{"module.base.address = 'a65d800000'"}, nil, nil}, + ModuleChecksum: {ModuleChecksum, "module checksum", params.Uint32, []string{"module.checksum = 746424"}, nil, nil}, + ModuleSize: {ModuleSize, "module size", params.Uint32, []string{"module.size > 1024"}, nil, nil}, + ModuleDefaultAddress: {ModuleDefaultAddress, "default module address", params.Address, []string{"module.default_address = '7efe0000'"}, nil, nil}, + ModulePID: {ModulePID, "target process identifier", params.Uint32, []string{"module.pid = 80"}, nil, nil}, + ModuleSignatureType: {ModuleSignatureType, "module signature type", params.AnsiString, []string{"module.signature.type != 'NONE'"}, nil, nil}, + ModuleSignatureLevel: {ModuleSignatureLevel, "module signature level", params.AnsiString, []string{"module.signature.level = 'AUTHENTICODE'"}, nil, nil}, + ModuleSignatureExists: {ModuleSignatureExists, "indicates if the module is signed", params.Bool, []string{"module.signature.exists = true"}, nil, nil}, + ModuleSignatureTrusted: {ModuleSignatureTrusted, "indicates if the module signature is trusted", params.Bool, []string{"module.signature.trusted = false"}, nil, nil}, + ModuleSignatureSerial: {ModuleSignatureSerial, "module certificate serial number", params.UnicodeString, []string{"module.signature.serial = '330000023241fb59996dcc4dff000000000232'"}, nil, nil}, + ModuleSignatureSubject: {ModuleSignatureSubject, "module certificate subject", params.UnicodeString, []string{"module.signature.subject contains 'Washington, Redmond, Microsoft Corporation'"}, nil, nil}, + ModuleSignatureIssuer: {ModuleSignatureIssuer, "module certificate CA", params.UnicodeString, []string{"module.signature.issuer contains 'Washington, Redmond, Microsoft Corporation'"}, nil, nil}, + ModuleSignatureAfter: {ModuleSignatureAfter, "module certificate expiration date", params.Time, []string{"module.signature.after contains '2024-02-01 00:05:42 +0000 UTC'"}, nil, nil}, + ModuleSignatureBefore: {ModuleSignatureBefore, "module certificate enrollment date", params.Time, []string{"module.signature.before contains '2024-02-01 00:05:42 +0000 UTC'"}, nil, nil}, + ModuleIsDLL: {ModuleIsDLL, "indicates if the loaded module is a DLL", params.Bool, []string{"module.is_dll'"}, nil, nil}, + ModuleIsDriver: {ModuleIsDriver, "indicates if the loaded module is a driver", params.Bool, []string{"module.is_driver'"}, nil, nil}, + ModuleIsExecutable: {ModuleIsExecutable, "indicates if the loaded module is an executable", params.Bool, []string{"module.is_exec'"}, nil, nil}, + ModuleIsDotnet: {ModuleIsDotnet, "indicates if the loaded module is a .NET assembly", params.Bool, []string{"module.pe.is_dotnet'"}, nil, nil}, + DllPath: {DllPath, "full dll path", params.UnicodeString, []string{"dll.path = 'C:\\Windows\\System32\\advapi32.dll'"}, nil, nil}, + DllPathStem: {DllPathStem, "dll path stem", params.UnicodeString, []string{"dll.path.stem = 'C:\\Windows\\System32\\advapi32'"}, nil, nil}, + DllName: {DllName, "module name", params.UnicodeString, []string{"dll.name = 'advapi32.dll'"}, nil, nil}, + DllBase: {DllBase, "the base address of process in which the DLL is loaded", params.Address, []string{"dll.base = 'a65d800000'"}, nil, nil}, + DllSize: {DllSize, "dll virtual mapped size", params.Uint32, []string{"dll.size > 1024"}, nil, nil}, + DllPID: {DllPID, "target process identifier", params.Uint32, []string{"dll.pid = 80"}, nil, nil}, + DllSignatureType: {DllSignatureType, "dll signature type", params.AnsiString, []string{"dll.signature.type != 'NONE'"}, nil, nil}, + DllSignatureLevel: {DllSignatureLevel, "dll signature level", params.AnsiString, []string{"dll.signature.level = 'AUTHENTICODE'"}, nil, nil}, + DllSignatureExists: {DllSignatureExists, "indicates if the dll is signed", params.Bool, []string{"dll.signature.exists = true"}, nil, nil}, + DllSignatureTrusted: {DllSignatureTrusted, "indicates if the dll signature is trusted", params.Bool, []string{"dll.signature.trusted = false"}, nil, nil}, + DllSignatureSerial: {DllSignatureSerial, "dll certificate serial number", params.UnicodeString, []string{"dll.signature.serial = '330000023241fb59996dcc4dff000000000232'"}, nil, nil}, + DllSignatureSubject: {DllSignatureSubject, "dll certificate subject", params.UnicodeString, []string{"dll.signature.subject contains 'Washington, Redmond, Microsoft Corporation'"}, nil, nil}, + DllSignatureIssuer: {DllSignatureIssuer, "dll certificate CA", params.UnicodeString, []string{"dll.signature.issuer contains 'Washington, Redmond, Microsoft Corporation'"}, nil, nil}, + DllSignatureAfter: {DllSignatureAfter, "moddllule certificate expiration date", params.Time, []string{"dll.signature.after contains '2024-02-01 00:05:42 +0000 UTC'"}, nil, nil}, + DllSignatureBefore: {DllSignatureBefore, "dll certificate enrollment date", params.Time, []string{"dll.signature.before contains '2024-02-01 00:05:42 +0000 UTC'"}, nil, nil}, + DllIsDotnet: {DllIsDotnet, "indicates if the loaded dll is a .NET assembly", params.Bool, []string{"dll.pe.is_dotnet'"}, nil, nil}, + + FileObject: {FileObject, "file object address", params.Uint64, []string{"file.object = 18446738026482168384"}, nil, nil}, + FilePath: {FilePath, "full file path", params.UnicodeString, []string{"file.path = 'C:\\Windows\\System32'"}, nil, nil}, + FilePathStem: {FilePathStem, "full file path without extension", params.UnicodeString, []string{"file.path.stem = 'C:\\Windows\\System32\\cmd'"}, nil, nil}, + FileName: {FileName, "full file name", params.UnicodeString, []string{"file.name contains 'mimikatz'"}, nil, nil}, + FileOperation: {FileOperation, "file operation", params.AnsiString, []string{"file.operation = 'open'"}, nil, nil}, + FileShareMask: {FileShareMask, "file share mask", params.AnsiString, []string{"file.share.mask = 'READ'"}, &Deprecation{Since: "3.1.0", Fields: []Field{FileShareMode}}, nil}, + FileShareMode: {FileShareMask, "file share mode", params.AnsiString, []string{"file.share_mode = 'DENY'"}, nil, nil}, + FileIOSize: {FileIOSize, "file I/O size", params.Uint32, []string{"file.io.size > 512"}, nil, nil}, + FileOffset: {FileOffset, "file offset", params.Uint64, []string{"file.offset = 1024"}, nil, nil}, + FileType: {FileType, "file type", params.AnsiString, []string{"file.type = 'directory'"}, nil, nil}, + FileExtension: {FileExtension, "file extension", params.AnsiString, []string{"file.extension = '.dll'"}, nil, nil}, + FileAttributes: {FileAttributes, "file attributes", params.Slice, []string{"file.attributes in ('archive', 'hidden')"}, nil, nil}, + FileStatus: {FileStatus, "file operation status message", params.UnicodeString, []string{"file.status != 'success'"}, nil, nil}, + FileViewBase: {FileViewBase, "view base address", params.Address, []string{"file.view.base = '25d42170000'"}, nil, nil}, + FileViewSize: {FileViewSize, "size of the mapped view", params.Uint64, []string{"file.view.size > 1024"}, nil, nil}, + FileViewType: {FileViewType, "type of the mapped view section", params.Enum, []string{"file.view.type = 'IMAGE'"}, nil, nil}, + FileViewProtection: {FileViewProtection, "protection rights of the section view", params.AnsiString, []string{"file.view.protection = 'READONLY'"}, nil, nil}, + FileIsDLL: {FileIsDLL, "indicates if the created file is a DLL", params.Bool, []string{"file.is_dll'"}, nil, nil}, + FileIsDriver: {FileIsDriver, "indicates if the created file is a driver", params.Bool, []string{"file.is_driver'"}, nil, nil}, + FileIsExecutable: {FileIsExecutable, "indicates if the created file is an executable", params.Bool, []string{"file.is_exec'"}, nil, nil}, + FilePID: {FilePID, "denotes the process id performing file operation", params.PID, []string{"file.pid = 4"}, nil, nil}, + FileKey: {FileKey, "uniquely identifies the file object", params.Uint64, []string{"file.key = 12446738026482168384"}, nil, nil}, + FileInfoClass: {FileInfoClass, "identifies the file information class", params.Enum, []string{"file.info_class = 'Allocation'"}, nil, nil}, + FileInfoAllocationSize: {FileInfoAllocationSize, "file allocation size", params.Uint64, []string{"file.info.allocation_size > 645400"}, nil, nil}, + FileInfoEOFSize: {FileInfoEOFSize, "file EOF size", params.Uint64, []string{"file.info.eof_size > 1000"}, nil, nil}, + FileInfoIsDispositionDeleteFile: {FileInfoIsDispositionDeleteFile, "indicates if the file is deleted when its handle is closed", params.Bool, []string{"file.info.is_disposition_file_delete = true"}, nil, nil}, + + RegistryPath: {RegistryPath, "fully qualified registry path", params.UnicodeString, []string{"registry.path = 'HKEY_LOCAL_MACHINE\\SYSTEM'"}, nil, nil}, + RegistryKeyName: {RegistryKeyName, "registry key name", params.UnicodeString, []string{"registry.key.name = 'CurrentControlSet'"}, nil, nil}, + RegistryKCB: {RegistryKCB, "registry KCB address", params.Address, []string{"registry.kcb = 'FFFFB905D60C2268'"}, nil, nil}, + RegistryValue: {RegistryValue, "registry value name", params.UnicodeString, []string{"registry.value = 'Epoch'"}, nil, nil}, + RegistryValueType: {RegistryValueType, "type of registry value", params.UnicodeString, []string{"registry.value.type = 'REG_SZ'"}, nil, nil}, + RegistryData: {RegistryData, "registry value captured data", params.Object, []string{"registry.data = '%SystemRoot%'"}, nil, nil}, + RegistryStatus: {RegistryStatus, "status of registry operation", params.UnicodeString, []string{"registry.status != 'success'"}, nil, nil}, + + NetDIP: {NetDIP, "destination IP address", params.IP, []string{"net.dip = 172.17.0.3"}, nil, nil}, + NetSIP: {NetSIP, "source IP address", params.IP, []string{"net.sip = 127.0.0.1"}, nil, nil}, + NetDport: {NetDport, "destination port", params.Uint16, []string{"net.dport in (80, 443, 8080)"}, nil, nil}, + NetSport: {NetSport, "source port", params.Uint16, []string{"net.sport != 3306"}, nil, nil}, + NetDportName: {NetDportName, "destination port name", params.AnsiString, []string{"net.dport.name = 'dns'"}, nil, nil}, + NetSportName: {NetSportName, "source port name", params.AnsiString, []string{"net.sport.name = 'http'"}, nil, nil}, + NetL4Proto: {NetL4Proto, "layer 4 protocol name", params.AnsiString, []string{"net.l4.proto = 'TCP"}, nil, nil}, + NetPacketSize: {NetPacketSize, "packet size", params.Uint32, []string{"net.size > 512"}, nil, nil}, + NetSIPNames: {NetSIPNames, "source IP names", params.Slice, []string{"net.sip.names in ('github.com.')"}, nil, nil}, + NetDIPNames: {NetDIPNames, "destination IP names", params.Slice, []string{"net.dip.names in ('github.com.')"}, nil, nil}, + + HandleID: {HandleID, "handle identifier", params.Uint16, []string{"handle.id = 24"}, nil, nil}, + HandleObject: {HandleObject, "handle object address", params.Address, []string{"handle.object = 'FFFFB905DBF61988'"}, nil, nil}, + HandleName: {HandleName, "handle name", params.UnicodeString, []string{"handle.name = '\\Device\\NamedPipe\\chrome.12644.28.105826381'"}, nil, nil}, + HandleType: {HandleType, "handle type", params.AnsiString, []string{"handle.type = 'Mutant'"}, nil, nil}, + + PeNumSections: {PeNumSections, "number of sections", params.Uint16, []string{"pe.nsections < 5"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsPeNumSections}}, nil}, + PeNumSymbols: {PeNumSymbols, "number of entries in the symbol table", params.Uint32, []string{"pe.nsymbols > 230"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsPeNumSymbols}}, nil}, + PeBaseAddress: {PeBaseAddress, "image base address", params.Address, []string{"pe.address.base = '140000000'"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsPeBaseAddress}}, nil}, + PeEntrypoint: {PeEntrypoint, "address of the entrypoint function", params.Address, []string{"pe.address.entrypoint = '20110'"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsPeEntrypoint}}, nil}, + PeSymbols: {PeSymbols, "imported symbols", params.Slice, []string{"pe.symbols in ('GetTextFaceW', 'GetProcessHeap')"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsPeSymbols}}, nil}, + PeImports: {PeImports, "imported dynamic linked libraries", params.Slice, []string{"pe.imports in ('msvcrt.dll', 'GDI32.dll'"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsPeImports}}, nil}, + + PeResources: {PeResources, "version resources", params.Map, []string{"pe.resources[FileDescription] = 'Notepad'"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsPeResources}}, &Argument{Optional: true, Pattern: "[a-zA-Z0-9_]+", ValidationFunc: func(s string) bool { + for _, c := range s { + switch { + case unicode.IsLower(c): + case unicode.IsUpper(c): + case unicode.IsNumber(c): + case c == '_': + default: + return false + } + } + return true + }}}, + + PeCompany: {PeCompany, "internal company name of the file provided at compile-time", params.UnicodeString, []string{"pe.company = 'Microsoft Corporation'"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsPeCompany}}, nil}, + PeCopyright: {PeCopyright, "copyright notice for the file emitted at compile-time", params.UnicodeString, []string{"pe.copyright = '© Microsoft Corporation'"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsPeCopyright}}, nil}, + PeDescription: {PeDescription, "internal description of the file provided at compile-time", params.UnicodeString, []string{"pe.description = 'Notepad'"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsPeDescription}}, nil}, + PeFileName: {PeFileName, "original file name supplied at compile-time", params.UnicodeString, []string{"pe.file.name = 'NOTEPAD.EXE'"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsPeFileName}}, nil}, + PeFileVersion: {PeFileVersion, "file version supplied at compile-time", params.UnicodeString, []string{"pe.file.version = '10.0.18362.693 (WinBuild.160101.0800)'"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsPeFileVersion}}, nil}, + PeProduct: {PeProduct, "internal product name of the file provided at compile-time", params.UnicodeString, []string{"pe.product = 'Microsoft® Windows® Operating System'"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsPeProduct}}, nil}, + PeProductVersion: {PeProductVersion, "internal product version of the file provided at compile-time", params.UnicodeString, []string{"pe.product.version = '10.0.18362.693'"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsPeProductVersion}}, nil}, + PeIsDLL: {PeIsDLL, "indicates if the loaded image or created file is a DLL", params.Bool, []string{"pe.is_dll'"}, &Deprecation{Since: "2.0.0", Fields: []Field{FileIsDLL, ImageIsDLL}}, nil}, + PeIsDriver: {PeIsDriver, "indicates if the loaded image or created file is a driver", params.Bool, []string{"pe.is_driver'"}, &Deprecation{Since: "2.0.0", Fields: []Field{FileIsDriver, ImageIsDriver}}, nil}, + PeIsExecutable: {PeIsExecutable, "indicates if the loaded image or created file is an executable", params.Bool, []string{"pe.is_exec'"}, &Deprecation{Since: "2.0.0", Fields: []Field{FileIsExecutable, ImageIsExecutable}}, nil}, + PeImphash: {PeImphash, "import hash", params.AnsiString, []string{"pe.impash = '5d3861c5c547f8a34e471ba273a732b2'"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsPeImphash}}, nil}, + PeIsDotnet: {PeIsDotnet, "indicates if PE contains CLR data", params.Bool, []string{"pe.is_dotnet"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsPeIsDotnet}}, nil}, + PeAnomalies: {PeAnomalies, "contains PE anomalies detected during parsing", params.Slice, []string{"pe.anomalies in ('number of sections is 0')"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsPeAnomalies}}, nil}, + PeIsSigned: {PeIsSigned, "indicates if the PE has embedded or catalog signature", params.Bool, []string{"pe.is_signed"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsSignatureExists}}, nil}, + PeIsTrusted: {PeIsTrusted, "indicates if the PE certificate chain is trusted", params.Bool, []string{"pe.is_trusted"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsSignatureTrusted}}, nil}, + PeCertSerial: {PeCertSerial, "PE certificate serial number", params.UnicodeString, []string{"pe.cert.serial = '330000023241fb59996dcc4dff000000000232'"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsSignatureSerial}}, nil}, + PeCertSubject: {PeCertSubject, "PE certificate subject", params.UnicodeString, []string{"pe.cert.subject contains 'Washington, Redmond, Microsoft Corporation'"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsSignatureSubject}}, nil}, + PeCertIssuer: {PeCertIssuer, "PE certificate CA", params.UnicodeString, []string{"pe.cert.issuer contains 'Washington, Redmond, Microsoft Corporation'"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsSignatureIssuer}}, nil}, + PeCertAfter: {PeCertAfter, "PE certificate expiration date", params.Time, []string{"pe.cert.after contains '2024-02-01 00:05:42 +0000 UTC'"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsSignatureAfter}}, nil}, + PeCertBefore: {PeCertBefore, "PE certificate enrollment date", params.Time, []string{"pe.cert.before contains '2024-02-01 00:05:42 +0000 UTC'"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsSignatureBefore}}, nil}, + PeIsModified: {PeIsModified, "indicates if disk and in-memory PE headers differ", params.Bool, []string{"pe.is_modified"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsPeIsModified}}, nil}, + + MemBaseAddress: {MemBaseAddress, "region base address", params.Address, []string{"mem.address = '211d13f2000'"}, nil, nil}, + MemRegionSize: {MemRegionSize, "region size", params.Uint64, []string{"mem.size > 438272"}, nil, nil}, + MemAllocType: {MemAllocType, "region allocation or release type", params.Flags, []string{"mem.alloc = 'COMMIT'"}, nil, nil}, + MemPageType: {MemPageType, "page type of the allocated region", params.Enum, []string{"mem.type = 'PRIVATE'"}, nil, nil}, + MemProtection: {MemProtection, "allocated region protection type", params.Enum, []string{"mem.protection = 'READWRITE'"}, nil, nil}, + MemProtectionMask: {MemProtectionMask, "allocated region protection in mask notation", params.Enum, []string{"mem.protection.mask = 'RWX'"}, nil, nil}, + + DNSName: {DNSName, "dns query name", params.UnicodeString, []string{"dns.name = 'example.org'"}, nil, nil}, + DNSRR: {DNSRR, "dns resource record type", params.AnsiString, []string{"dns.rr = 'AA'"}, nil, nil}, + DNSOptions: {DNSOptions, "dns query options", params.Flags64, []string{"dns.options in ('ADDRCONFIG', 'DUAL_ADDR')"}, nil, nil}, + DNSRcode: {DNSRR, "dns response status", params.AnsiString, []string{"dns.rcode = 'NXDOMAIN'"}, nil, nil}, + DNSAnswers: {DNSAnswers, "dns response answers", params.Slice, []string{"dns.answers in ('o.lencr.edgesuite.net', 'a1887.dscq.akamai.net')"}, nil, nil}, + + ThreadpoolPoolID: {ThreadpoolPoolID, "thread pool identifier", params.Address, []string{"threadpool.id = '20f5fc02440'"}, nil, nil}, + ThreadpoolTaskID: {ThreadpoolTaskID, "thread pool task identifier", params.Address, []string{"threadpool.task.id = '20f7ecd21f8'"}, nil, nil}, + ThreadpoolCallbackAddress: {ThreadpoolCallbackAddress, "thread pool callback address", params.Address, []string{"threadpool.callback.address = '7ff868739ed0'"}, nil, nil}, + ThreadpoolCallbackSymbol: {ThreadpoolCallbackSymbol, "thread pool callback symbol", params.UnicodeString, []string{"threadpool.callback.symbol = 'RtlDestroyQueryDebugBuffer'"}, nil, nil}, + ThreadpoolCallbackModule: {ThreadpoolCallbackModule, "thread pool module containing the callback symbol", params.UnicodeString, []string{"threadpool.callback.module contains 'ntdll.dll'"}, nil, nil}, + ThreadpoolCallbackContext: {ThreadpoolCallbackContext, "thread pool callback context address", params.Address, []string{"threadpool.callback.context = '1df41e07bd0'"}, nil, nil}, + ThreadpoolCallbackContextRip: {ThreadpoolCallbackContextRip, "thread pool callback thread context instruction pointer", params.Address, []string{"threadpool.callback.context.rip = '1df42ffc1f8'"}, nil, nil}, + ThreadpoolCallbackContextRipSymbol: {ThreadpoolCallbackContextRipSymbol, "thread pool callback thread context instruction pointer symbol", params.UnicodeString, []string{"threadpool.callback.context.rip.symbol = 'VirtualProtect'"}, nil, nil}, + ThreadpoolCallbackContextRipModule: {ThreadpoolCallbackContextRipModule, "thread pool callback thread context instruction pointer symbol module", params.UnicodeString, []string{"threadpool.callback.context.rip.module contains 'ntdll.dll'"}, nil, nil}, + ThreadpoolSubprocessTag: {ThreadpoolSubprocessTag, "thread pool service identifier", params.Address, []string{"threadpool.subprocess_tag = '10d'"}, nil, nil}, + ThreadpoolTimerDuetime: {ThreadpoolTimerDuetime, "thread pool timer due time", params.Uint64, []string{"threadpool.timer.duetime > 10"}, nil, nil}, + ThreadpoolTimerSubqueue: {ThreadpoolTimerSubqueue, "thread pool timer subqueue address", params.Address, []string{"threadpool.timer.subqueue = '1db401703e8'"}, nil, nil}, + ThreadpoolTimer: {ThreadpoolTimer, "thread pool timer address", params.Address, []string{"threadpool.timer.address = '3e8'"}, nil, nil}, + ThreadpoolTimerPeriod: {ThreadpoolTimerPeriod, "thread pool timer period", params.Uint32, []string{"threadpool.timer.period = 0'"}, nil, nil}, + ThreadpoolTimerWindow: {ThreadpoolTimerWindow, "thread pool timer tolerate period", params.Uint32, []string{"threadpool.timer.window = 0'"}, nil, nil}, + ThreadpoolTimerAbsolute: {ThreadpoolTimerAbsolute, "indicates if the thread pool timer is absolute or relative", params.Bool, []string{"threadpool.timer.is_absolute = true'"}, nil, nil}, +} + +// ArgumentOf returns argument data for the specified field. +func ArgumentOf(name string) *Argument { + f, ok := fields[Field(name)] + if !ok { + // this can happen for pseudo fields + return nil + } + return f.Argument +} + +// IsField returns true if the provided string is a +// recognized field or pseudo field. Otherwise, it +// returns false. +func IsField(name string) bool { + if _, ok := fields[Field(name)]; ok || IsPseudoField(Field(name)) { + return true + } + return false +} diff --git a/pkg/filter/filter_test.go b/pkg/filter/filter_test.go index ecf7ac0d4..a7a77e48b 100644 --- a/pkg/filter/filter_test.go +++ b/pkg/filter/filter_test.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2019-2020 by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/pkg/filter/ql/functions/get_reg_value_test.go b/pkg/filter/ql/functions/get_reg_value_test.go index 659475da4..5ff6c5b3a 100644 --- a/pkg/filter/ql/functions/get_reg_value_test.go +++ b/pkg/filter/ql/functions/get_reg_value_test.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2021-2022 by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/pkg/filter/ql/functions/minidump.go b/pkg/filter/ql/functions/minidump.go index 1c9ae4fba..4a10a7f4d 100644 --- a/pkg/filter/ql/functions/minidump.go +++ b/pkg/filter/ql/functions/minidump.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2021-2022 by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/pkg/fs/file_class.go b/pkg/fs/file_class.go index bef4b028b..d7a7658cd 100644 --- a/pkg/fs/file_class.go +++ b/pkg/fs/file_class.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2021-2022 by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/pkg/outputs/eventlog/api.go b/pkg/outputs/eventlog/api.go index 4b10baf88..6ecb053d0 100644 --- a/pkg/outputs/eventlog/api.go +++ b/pkg/outputs/eventlog/api.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2012 The Go Authors. All rights reserved. * Use of this source code is governed by a BSD-style diff --git a/pkg/outputs/eventlog/config.go b/pkg/outputs/eventlog/config.go index d67576cfb..3cab676a0 100644 --- a/pkg/outputs/eventlog/config.go +++ b/pkg/outputs/eventlog/config.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2021-2022 by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/pkg/outputs/eventlog/eventlog.go b/pkg/outputs/eventlog/eventlog.go index 941ca7014..02a6c1cd1 100644 --- a/pkg/outputs/eventlog/eventlog.go +++ b/pkg/outputs/eventlog/eventlog.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2021-2022 by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/pkg/outputs/eventlog/eventlog_test.go b/pkg/outputs/eventlog/eventlog_test.go index 2528d45e1..da04ef642 100644 --- a/pkg/outputs/eventlog/eventlog_test.go +++ b/pkg/outputs/eventlog/eventlog_test.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2021-2022 by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/pkg/pe/header.go b/pkg/pe/header.go index 9e9d30e3b..32584f506 100644 --- a/pkg/pe/header.go +++ b/pkg/pe/header.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2021-2022 by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/pkg/pe/header_test.go b/pkg/pe/header_test.go index db97a6a5f..f09b8f206 100644 --- a/pkg/pe/header_test.go +++ b/pkg/pe/header_test.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2021-2022 by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/pkg/pe/parser.go b/pkg/pe/parser.go index d8a42be33..5606681a1 100644 --- a/pkg/pe/parser.go +++ b/pkg/pe/parser.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2021-2022 by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/pkg/pe/parser_test.go b/pkg/pe/parser_test.go index 28e3fe645..ab4871075 100644 --- a/pkg/pe/parser_test.go +++ b/pkg/pe/parser_test.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2021-2022 by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/pkg/rules/compiler_test.go b/pkg/rules/compiler_test.go index 404bf0c64..21455bc2b 100644 --- a/pkg/rules/compiler_test.go +++ b/pkg/rules/compiler_test.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2021-present by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/pkg/rules/engine_test.go b/pkg/rules/engine_test.go index 21bdc4250..4c4ee43b3 100644 --- a/pkg/rules/engine_test.go +++ b/pkg/rules/engine_test.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2021-present by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/pkg/rules/sequence_test.go b/pkg/rules/sequence_test.go index eb6397f55..c33aded23 100644 --- a/pkg/rules/sequence_test.go +++ b/pkg/rules/sequence_test.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2021-present by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/pkg/sys/dbghelp.go b/pkg/sys/dbghelp.go index 76a82b88a..7e3d1d666 100644 --- a/pkg/sys/dbghelp.go +++ b/pkg/sys/dbghelp.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2021-2022 by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/pkg/sys/device.go b/pkg/sys/device.go index 7792f3fdc..f6e37bf4f 100644 --- a/pkg/sys/device.go +++ b/pkg/sys/device.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2021-2022 by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/pkg/sys/device_test.go b/pkg/sys/device_test.go index 3fad62088..3cd882fd4 100644 --- a/pkg/sys/device_test.go +++ b/pkg/sys/device_test.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2021-2022 by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/pkg/sys/doc.go b/pkg/sys/doc.go index d6c5f3682..7ed29f652 100644 --- a/pkg/sys/doc.go +++ b/pkg/sys/doc.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2019-2020 by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/pkg/sys/fs.go b/pkg/sys/fs.go index 62bcc074e..bc776181b 100644 --- a/pkg/sys/fs.go +++ b/pkg/sys/fs.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2021-2022 by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/pkg/sys/handle.go b/pkg/sys/handle.go index f52ee778d..a6a500843 100644 --- a/pkg/sys/handle.go +++ b/pkg/sys/handle.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2021-2022 by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/pkg/sys/mem.go b/pkg/sys/mem.go index 27ad1d1ac..4118d0b64 100644 --- a/pkg/sys/mem.go +++ b/pkg/sys/mem.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2021-2022 by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/pkg/sys/object.go b/pkg/sys/object.go index 4ff2ae9a7..d2530515d 100644 --- a/pkg/sys/object.go +++ b/pkg/sys/object.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2021-2022 by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/pkg/sys/privilege.go b/pkg/sys/privilege.go index fc331ce20..45f2ab5a5 100644 --- a/pkg/sys/privilege.go +++ b/pkg/sys/privilege.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2021-2022 by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/pkg/sys/process.go b/pkg/sys/process.go index 08af5ea9f..977f8fddd 100644 --- a/pkg/sys/process.go +++ b/pkg/sys/process.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2021-2022 by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/pkg/sys/process_test.go b/pkg/sys/process_test.go index 89f1503b1..720444440 100644 --- a/pkg/sys/process_test.go +++ b/pkg/sys/process_test.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2021-present by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/pkg/sys/rid.go b/pkg/sys/rid.go index 1c60763de..fcc8d3536 100644 --- a/pkg/sys/rid.go +++ b/pkg/sys/rid.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2021-present by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/pkg/sys/shell.go b/pkg/sys/shell.go index fb9b3d0fe..3f333004b 100644 --- a/pkg/sys/shell.go +++ b/pkg/sys/shell.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2021-2022 by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/pkg/sys/syscall.go b/pkg/sys/syscall.go index aeac71b66..bdfafbb30 100644 --- a/pkg/sys/syscall.go +++ b/pkg/sys/syscall.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2021-2022 by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/pkg/sys/trust.go b/pkg/sys/trust.go index ce28d867a..89a8f9ce4 100644 --- a/pkg/sys/trust.go +++ b/pkg/sys/trust.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2021-2022 by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/pkg/sys/trust_test.go b/pkg/sys/trust_test.go index f4bcceafa..a603f5efd 100644 --- a/pkg/sys/trust_test.go +++ b/pkg/sys/trust_test.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2021-2022 by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/pkg/sys/util.go b/pkg/sys/util.go index a159aee65..734f7866f 100644 --- a/pkg/sys/util.go +++ b/pkg/sys/util.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2021-2022 by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/pkg/sys/window.go b/pkg/sys/window.go index 05706fec1..3b1c595e7 100644 --- a/pkg/sys/window.go +++ b/pkg/sys/window.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2021-2022 by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/pkg/sys/wts.go b/pkg/sys/wts.go index 872d21ef1..2caeccd95 100644 --- a/pkg/sys/wts.go +++ b/pkg/sys/wts.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2021-2022 by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/pkg/sys/zsyscall_windows.go b/pkg/sys/zsyscall_windows.go index ca8c39bd3..7cd596c99 100644 --- a/pkg/sys/zsyscall_windows.go +++ b/pkg/sys/zsyscall_windows.go @@ -1,3 +1,5 @@ +//go:build windows + // Code generated by 'go generate'; DO NOT EDIT. package sys diff --git a/pkg/util/colorizer/colorizer.go b/pkg/util/colorizer/colorizer.go index 6f70c1996..2081b82cb 100644 --- a/pkg/util/colorizer/colorizer.go +++ b/pkg/util/colorizer/colorizer.go @@ -22,8 +22,6 @@ import ( "os" "runtime" "strings" - - "golang.org/x/sys/windows" ) // escape sequences @@ -122,20 +120,3 @@ func IsAnsiEnabled() bool { } return true } - -// enableWindowsVT activates ENABLE_VIRTUAL_TERMINAL_PROCESSING on the Windows -// console handle so that ANSI escape sequences are interpreted rather than -// printed verbatim. Returns false on pre-Windows 10 hosts where this flag -// is unavailable. -func enableWindowsVT() bool { - handle := windows.Handle(os.Stdout.Fd()) - var mode uint32 - if err := windows.GetConsoleMode(handle, &mode); err != nil { - return false - } - const vtFlag = 0x0004 // ENABLE_VIRTUAL_TERMINAL_PROCESSING - if mode&vtFlag != 0 { - return true - } - return windows.SetConsoleMode(handle, mode|vtFlag) == nil -} diff --git a/pkg/util/colorizer/colorizer_stub.go b/pkg/util/colorizer/colorizer_stub.go new file mode 100644 index 000000000..81c41e660 --- /dev/null +++ b/pkg/util/colorizer/colorizer_stub.go @@ -0,0 +1,23 @@ +//go:build !windows + +/* + * Copyright 2026 by Nedim Sabic Sabic + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package colorizer + +func enableWindowsVT() bool { return false } diff --git a/pkg/util/colorizer/colorizer_windows.go b/pkg/util/colorizer/colorizer_windows.go new file mode 100644 index 000000000..7018ef0fc --- /dev/null +++ b/pkg/util/colorizer/colorizer_windows.go @@ -0,0 +1,44 @@ +//go:build windows + +/* + * Copyright 2021-present by Nedim Sabic Sabic + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package colorizer + +import ( + "os" + + "golang.org/x/sys/windows" +) + +// enableWindowsVT activates ENABLE_VIRTUAL_TERMINAL_PROCESSING on the Windows +// console handle so that ANSI escape sequences are interpreted rather than +// printed verbatim. Returns false on pre-Windows 10 hosts where this flag +// is unavailable. +func enableWindowsVT() bool { + handle := windows.Handle(os.Stdout.Fd()) + var mode uint32 + if err := windows.GetConsoleMode(handle, &mode); err != nil { + return false + } + const vtFlag = 0x0004 // ENABLE_VIRTUAL_TERMINAL_PROCESSING + if mode&vtFlag != 0 { + return true + } + return windows.SetConsoleMode(handle, mode|vtFlag) == nil +} diff --git a/pkg/util/eventlog/eventid.go b/pkg/util/eventlog/eventid.go index f65617e88..f63511821 100644 --- a/pkg/util/eventlog/eventid.go +++ b/pkg/util/eventlog/eventid.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2021-2022 by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/pkg/util/eventlog/eventid_test.go b/pkg/util/eventlog/eventid_test.go index 9797676ae..04ce8561c 100644 --- a/pkg/util/eventlog/eventid_test.go +++ b/pkg/util/eventlog/eventid_test.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2021-2022 by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/pkg/util/eventlog/eventlog.go b/pkg/util/eventlog/eventlog.go index 7ee583ddd..f48eb3196 100644 --- a/pkg/util/eventlog/eventlog.go +++ b/pkg/util/eventlog/eventlog.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2021-2022 by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/pkg/config/eventsource_linux_stub.go b/pkg/util/ntstatus/status_linux.go similarity index 55% rename from pkg/config/eventsource_linux_stub.go rename to pkg/util/ntstatus/status_linux.go index 1b61dfc0a..5c0e02286 100644 --- a/pkg/config/eventsource_linux_stub.go +++ b/pkg/util/ntstatus/status_linux.go @@ -1,4 +1,4 @@ -//go:build linux && !eventsource +//go:build linux /* * Copyright 2026 by Nedim Sabic Sabic @@ -18,24 +18,18 @@ * limitations under the License. */ -package config +package ntstatus -import ( - "github.com/spf13/pflag" - "github.com/spf13/viper" -) +import "fmt" -type EventSourceConfig struct { - EnableProcessEvents bool - EnableFileIOEvents bool - EnableNetEvents bool - EnableMemEvents bool -} - -func (c *EventSourceConfig) AddFlags(flags *pflag.FlagSet) { - flags.Bool("eventsource.enable-process", true, "Determines whether process events are collected") -} +// Success determines the success system message +const Success = "Success" -func (c *EventSourceConfig) initFromViper(v *viper.Viper) { - c.EnableProcessEvents = v.GetBool("eventsource.enable-process") +// FormatMessage resolves a status code to a human-readable message. +// On Linux this returns a hex representation for non-zero codes. +func FormatMessage(status uint32) string { + if status == 0 { + return Success + } + return fmt.Sprintf("0x%x", status) } diff --git a/pkg/util/ntstatus/status.go b/pkg/util/ntstatus/status_windows.go similarity index 99% rename from pkg/util/ntstatus/status.go rename to pkg/util/ntstatus/status_windows.go index b7506c51e..6aaaa2b0c 100644 --- a/pkg/util/ntstatus/status.go +++ b/pkg/util/ntstatus/status_windows.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2021-2022 by Nedim Sabic Sabic * https://www.fibratus.io From 378513f1127eca33c68f0b6ef410e7525753f93a Mon Sep 17 00:00:00 2001 From: Mostafa Moradian Date: Sat, 8 Aug 2026 20:50:04 +0200 Subject: [PATCH 13/28] fix(build): Remove superseded Windows-gated catalog copies Drop the old _windows.go param and field catalogs now that the shared names live in platform-neutral files. --- pkg/event/params/params_windows.go | 302 ------- pkg/event/params/types_windows.go | 142 --- pkg/filter/fields/fields_windows.go | 1304 --------------------------- 3 files changed, 1748 deletions(-) delete mode 100644 pkg/event/params/params_windows.go delete mode 100644 pkg/event/params/types_windows.go delete mode 100644 pkg/filter/fields/fields_windows.go diff --git a/pkg/event/params/params_windows.go b/pkg/event/params/params_windows.go deleted file mode 100644 index cb269f02c..000000000 --- a/pkg/event/params/params_windows.go +++ /dev/null @@ -1,302 +0,0 @@ -/* - * Copyright 2019-2020 by Nedim Sabic Sabic - * https://www.fibratus.io - * All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package params - -const ( - // NTStatus is the parameter that identifies the NTSTATUS value. - NTStatus = "status" - - // ProcessID represents the process identifier. - ProcessID = "pid" - // TargetProcessID represents the target process identifier. - TargetProcessID = "target_pid" - // ProcessObject field represents the address of the process object in the kernel. - ProcessObject = "kproc" - // ThreadID field represents the thread identifier. - ThreadID = "tid" - // Callstack field represents the thread callstack. - Callstack = "callstack" - // CallstackTimestamp field identifvies the callstack timestamp parameter. - CallstackTimestamp = "callstack_timestamp" - // ProcessParentID field represents the parent process identifier. - ProcessParentID = "ppid" - // ProcessRealParentID field presents the real parent process identifier. - ProcessRealParentID = "real_ppid" - // SessionID fields represents the session identifier. - SessionID = "session_id" - // UserSID field is the security identifier associated to the process token under which it is run. - UserSID = "sid" - // Username field represents the username under which the event was generated. - Username = "username" - // Domain field represents the domain under which the event was generated. - Domain = "domain" - // ProcessName field denotes the process Module name. - ProcessName = "name" - // Exe field denotes the full path of the executable. - Exe = "exe" - // Cmdline field represents the process command line. - Cmdline = "cmdline" - // DTB field denotes the address of the process directory table. - DTB = "directory_table_base" - // ProcessFlags field denotes the process creation flags - ProcessFlags = "flags" - // ExitStatus is the field that represents the process exit status. - ExitStatus = "exit_status" - // StartTime field denotes the process start time. - StartTime = "start_time" - // ProcessTokenIntegrityLevel field denotes the process integrity level. - ProcessTokenIntegrityLevel = "token_integrity_level" - // ProcessTokenElevationType field designates the process token elevation type. - ProcessTokenElevationType = "token_elevation_type" - // ProcessTokenIsElevated field designates if the process token is elevated. - ProcessTokenIsElevated = "token_is_elevated" - - // DesiredAccess field denotes the access rights for different kernel objects such as processes or threads. - DesiredAccess = "desired_access" - - // BasePrio field is the thread base priority assigned by the scheduler. - BasePrio = "base_prio" - // IOPrio represents the filed that indicates the thread I/O priority. - IOPrio = "io_prio" - // PagePrio field denotes page priority. - PagePrio = "page_prio" - // KstackBase field is the start address of the kernel space stack. - KstackBase = "kstack" - // KstackLimit field is the end address of the kernel space stack. - KstackLimit = "kstack_limit" - // UstackBase field is the start address of the user space stack. - UstackBase = "ustack" - // UstackLimit field is the end address of the user space stack. - UstackLimit = "ustack_limit" - // StartAddress field is the thread start address. - StartAddress = "start_address" - // StartAddressSymbol field is the symbol associated with the thread start address. - StartAddressSymbol = "start_address_symbol" - // StartAddressModule field is the module where the thread start address is mapped. - StartAddressModule = "start_address_module" - // TEB field is the address of the Thread Environment Block (TEB) - TEB = "teb" - - // FileObject determines the field name for the file object pointer. - FileObject = "file_object" - // FilePath represents the field that designates the absolute path of the file. - FilePath = "file_path" - // FileCreateOptions is the field that represents the values passed in the CreateDispositions parameter to the NtCreateFile function. - FileCreateOptions = "create_options" - // FileOperation is the field that represents the values passed in the CreateOptions parameter to the NtCreateFile function. - FileOperation = "create_disposition" - // FileCreated represents the name for the file creation field. - FileCreated = "created" - // FileAccessed represents the name for the file access field. - FileAccessed = "accessed" - // FileModified represents the name for the file modification field. - FileModified = "modified" - // FileShareMask represents the field name for the share access mask. - FileShareMask = "share_mask" - // FileType represents the field name that indicates the file type. - FileType = "type" - // FileAttributes is the field that represents file attribute values. - FileAttributes = "attributes" - // FileIoSize is the filed that represents the number of bytes in file read/write operations. - FileIoSize = "io_size" - // FileOffset represents the file for the file offset in read/write operations. - FileOffset = "offset" - // FileInfoClass represents the file information class. - FileInfoClass = "class" - // FileKey represents the directory key identifier in EnumDirectory events. - FileKey = "file_key" - // FileDirectory represents the field for the directory name in EnumDirectory events. - FileDirectory = "directory" - // FileIrpPtr represents the I/O request packet id. - FileIrpPtr = "irp" - // FileExtraInfo is the parameter that represents extra information returned by the file system for the operation. For example for a read request, the actual number of bytes that were read. - FileExtraInfo = "extra_info" - // FileIsDLL is the parameter that indicates if the file is a DLL - FileIsDLL = "is_dll" - // FileIsDriver is the parameter that indicates if the file is a driver - FileIsDriver = "is_driver" - // FileIsExecutable is the parameter that indicates if the file is an executable - FileIsExecutable = "is_exec" - // FileIsDotnet is the parameter that indicates if the file is a .NET assembly - FileIsDotnet = "is_dotnet" - - // FileViewBase is the parameter that represents the base address of the mapped section. - FileViewBase = "view_base" - // FileViewSize is the parameter that represents the size of the mapped section. - FileViewSize = "view_size" - // FileViewSectionType is the parameter that represents the mapped section type. - FileViewSectionType = "section_type" - - // RegKeyHandle identifies the parameter name for the registry key handle. - RegKeyHandle = "key_handle" - // RegKCB identifies the parameter name for the registry key control block. - RegKCB = "kcb" - // RegPath represents the parameter name for the fully qualified key path. - RegPath = "key_path" - // RegValue identifies the parameter name that contains the value - RegValue = "value" - // RegValueType identifies the parameter that represents registry value type e.g (DWORD, BINARY) - RegValueType = "value_type" - // RegData identifies the parameter that stores the captured registry data - RegData = "data" - - // ModuleBase identifies the parameter name for the base address of the process in which the Mmdule is loaded. - ModuleBase = "base_address" - // ModuleSize represents the parameter name for the size of the module in bytes. - ModuleSize = "module_size" - // ModuleCheckSum is the parameter name for module checksum. - ModuleCheckSum = "checksum" - // ModuleTimeDateStamp is the parametter name for module timedate stamp. - ModuleTimeDateStamp = "timedate_stamp" - // ModuleDefaultBase is the parameter name that represents module's base address. - ModuleDefaultBase = "default_address" - // ModulePath is the parameter name that denotes the file path and extension of the DLL/executable Module. - ModulePath = "file_path" - // ModuleSignatureLevel is the parameter denoting the loaded module signature level. - ModuleSignatureLevel = "signature_level" - // ModuleSignatureType is the parameter denoting the loaded module signature type. - ModuleSignatureType = "signature_type" - // ModuleCertSubject is the parameter that indicates the subject of the certificate is the entity its public key is associated with. - ModuleCertSubject = "cert_subject" - // ModuleCertIssuer is the parameter that represents the certificate authority (CA). - ModuleCertIssuer = "cert_issuer" - // ModuleCertSerial is the parameter that represents the serial number MUST be a positive integer assigned - // by the CA to each certificate. - ModuleCertSerial = "cert_serial" - // ModuleCertNotBefore is the parameter that specifies the certificate won't be valid before this timestamp. - ModuleCertNotBefore = "cert_not_before" - // ModuleCertNotAfter is the parameter that specifies the certificate won't be valid after this timestamp. - ModuleCertNotAfter = "cert_not_after" - - // NetSize identifies the parameter name that represents the packet size. - NetSize = "size" - // NetDIP is the parameter name that denotes the destination IP address. - NetDIP = "dip" - // NetSIP is the parameter name that denotes the source IP address. - NetSIP = "sip" - // NetDport identifies the parameter name that represents destination port number. - NetDport = "dport" - // NetSport identifies the parameter name that represents source port number. - NetSport = "sport" - // NetMSS is the parameter name that represents the maximum TCP segment size. - NetMSS = "mss" - // NetRcvWin is the parameter name that represents TCP segment's receive window size. - NetRcvWin = "rcvwin" - // NetSAckopt is the parameter name that represents Selective Acknowledgment option in TCP header. - NetSAckopt = "sack_opt" - // NetTsopt is the parameter name that represents the time stamp option in TCP header. - NetTsopt = "timestamp_opt" - // NetWsopt is the parameter name that represents the window scale option in TCP header. - NetWsopt = "window_scale_opt" - // NetRcvWinScale is the parameter name that represents the TCP receive window scaling factor. - NetRcvWinScale = "recv_winscale" - // NetSendWinScale is the parameter name that represents the TCP send window scaling factor. - NetSendWinScale = "send_winscale" - // NetSeqNum is the parameter name that represents the TCP sequence number. - NetSeqNum = "seqnum" - // NetStartTime is the parameter name that represents the TCP start time. - NetStartTime = "start_time" - // NetEndTime is the parameter name that represents the TCP end time. - NetEndTime = "end_time" - // NetConnID is the parameter name that represents a unique connection identifier. - NetConnID = "connid" - // NetL4Proto is the parameter name that identifies the Layer 4 protocol name. - NetL4Proto = "l4_proto" - // NetDportName is the field that denotes the destination port name. - NetDportName = "dport_name" - // NetSportName is the field that denotes the source port name. - NetSportName = "sport_name" - // NetSIPNames is the field that denotes the source IP address names. - NetSIPNames = "sip_names" - // NetDIPNames is the field that denotes the destination IP address names. - NetDIPNames = "dip_names" - - // DNSName is the field that represents the DNS query name - DNSName = "name" - // DNSRR is the field that represents the DNS record type - DNSRR = "rr" - // DNSOpts is the field that represents the DNS options - DNSOpts = "options" - // DNSRcode is the field that represents the DNS response code - DNSRcode = "rcode" - // DNSAnswers is the field that represents DNS response answers - DNSAnswers = "answers" - - // HandleID identifies the parameter that specifies the handle identifier. - HandleID = "handle_id" - // HandleSourceID identifies the parameter that specifies the source handle identifier. - HandleSourceID = "handle_source_id" - // HandleObject identifies the parameter that represents the kernel object to which handle is associated. - HandleObject = "handle_object" - // HandleObjectName identifies the parameter that represents the kernel object name. - HandleObjectName = "handle_name" - // HandleObjectTypeID identifies the parameter that represents the kernel object type identifier. - HandleObjectTypeID = "type_id" - - // MemBaseAddress identifies the parameter that denotes the allocation base address. - MemBaseAddress = "base_address" - // MemRegionSize identifies the parameter that represents the allocated region size. - MemRegionSize = "region_size" - // MemAllocType identifies the parameter that represents allocation flags. - MemAllocType = "alloc_type" - // MemProtect identifies the parameter that represents the memory protection for the range of pages. - MemProtect = "protection" - // MemProtectMask identifies the parameter that represents the memory protection in mask notation - MemProtectMask = "protection_mask" - // MemPageType identifies the parameter that represents the allocated region type. - MemPageType = "page_type" - - // LinkSource identifies the parameter that represents the source symbolic link object or other kernel object - LinkSource = "source" - // LinkTarget identifies the parameter that represents the target symbolic link object or other kernel object - LinkTarget = "target" - - // ThreadpoolPoolID represents the thread pool identifier. - ThreadpoolPoolID = "pool_id" - // ThreadpoolTaskID represents the thread pool task identifier. - ThreadpoolTaskID = "task_id" - // ThreadpoolCallback represents the address of the callback function. - ThreadpoolCallback = "callback" - // ThreadpoolCallbackSymbol represents the callback symbol. - ThreadpoolCallbackSymbol = "callback_symbol" - // ThreadpoolCallbackModule represents the module containing the callback symbol. - ThreadpoolCallbackModule = "callback_module" - // ThreadpoolContext represents the address of the callback context. - ThreadpoolContext = "context" - // ThreadpoolContextRip represents the value of instruction pointer contained in the callback context. - ThreadpoolContextRip = "context_rip" - // ThreadpoolContextRipSymbol represents the symbol name associated with the instruction pointer in callback context. - ThreadpoolContextRipSymbol = "context_rip_symbol" - // ThreadpoolContextRipModule represents the module name associated with the instruction pointer in callback context. - ThreadpoolContextRipModule = "context_rip_module" - // ThreadpoolSubprocessTag represents the service identifier associated with the thread pool. - ThreadpoolSubprocessTag = "subprocess_tag" - // ThreadpoolTimerDuetime represents the timer due time. - ThreadpoolTimerDuetime = "duetime" - // ThreadpoolTimerSubqueue represents the memory address of the timer subqueue. - ThreadpoolTimerSubqueue = "subqueue" - // ThreadpoolTimer represents the memory address of the timer object. - ThreadpoolTimer = "timer" - // ThreadpoolTimerPeriod represents the period of the timer - ThreadpoolTimerPeriod = "period" - // ThreadpoolTimerWindow represents the timer tolerate period. - ThreadpoolTimerWindow = "window" - // ThreadpoolTimerAbsolute indicates if the timer is absolute or relative. - ThreadpoolTimerAbsolute = "absolute" -) diff --git a/pkg/event/params/types_windows.go b/pkg/event/params/types_windows.go deleted file mode 100644 index aec8c363d..000000000 --- a/pkg/event/params/types_windows.go +++ /dev/null @@ -1,142 +0,0 @@ -/* - * Copyright 2021-present by Nedim Sabic Sabic - * https://www.fibratus.io - * All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package params - -// Type defines event parameter type -type Type uint16 - -const ( - // Null is a null parameter type - Null Type = iota - // UnicodeString a string of 16-bit characters. By default, assumed to have been encoded using UTF-16LE - UnicodeString - // AnsiString a string of 8-bit characters - AnsiString - // Int8 a signed 8-bit integer - Int8 - // Uint8 an unsigned 8-bit integer - Uint8 - // Int16 a signed 16-bit integer - Int16 - // Uint16 an unsigned 16-bit integer - Uint16 - // Int32 a signed 32-bit integer - Int32 - // Uint32 an unsigned 32-bit integer - Uint32 - // Int64 a signed 64-bit integer - Int64 - // Uint64 an unsigned 64-bit integer - Uint64 - // Float an IEEE 4-byte floating-point number - Float - // Double an IEEE 8-byte floating-point number - Double - // Bool a 32-bit value where 0 is false and 1 is true - Bool - // Binary is a binary data of variable size. The size must be specified in the data definition as a constant or a reference to another (integer) data item.For an IP V6 address, the data should be an IN6_ADDR structure. - // For a socket address, the data should be a SOCKADDR_STORAGE structure. The AF_INET, AF_INET6, and AF_LINK address families are supported - Binary - // GUID is a GUID structure. On output, the GUID is rendered in the registry string form, {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} - GUID - // Pointer an unsigned 32-bit or 64-bit pointer value. The size depends on the architecture of the computer logging the event - Pointer - // SID a security identifier (SID) structure that uniquely identifies a user or group - SID - // PID is the process identifier - PID - // TID is the thread identifier - TID - // WbemSID is the Web-Based Enterprise Management security identifier. - WbemSID - // Port represents the endpoint port number - Port - // IP is the IP address - IP - // IPv4 is the IPv4 address - IPv4 - // IPv6 is the IPv6 address - IPv6 - // Time represents the timestamp - Time - // Slice represents a collection of items - Slice - // Enum represents an enumeration - Enum - // Map represents a map - Map - // Object is the generic object type - Object - // DOSPath represents the file system path in DOS device notation - DOSPath - // Path represents the file system path with normalized drive letter notation - Path - // Status represents the system error code message - Status - // Key represents the registry key - Key - // Flags represents a bitmask of flags - Flags - // Flags64 represents an extended (64 bits) bitmask of flags - Flags64 - // Address is the memory address reference - Address - // HandleType represents the handle type such as Mutex or File - HandleType -) - -// String return the type string representation. -func (t Type) String() string { - switch t { - case UnicodeString: - return "unicode" - case AnsiString: - return "ansi" - case Int8: - return "int8" - case Uint8: - return "uint8" - case Int16: - return "int16" - case Uint16: - return "uint16" - case Int32: - return "int32" - case Uint32: - return "uint32" - case Int64: - return "int64" - case Uint64: - return "uint64" - case SID, WbemSID: - return "sid" - case TID: - return "tid" - case PID: - return "pid" - case Port: - return "port" - case IPv6: - return "ipv6" - case IPv4: - return "ipv4" - default: - return "unknown" - } -} diff --git a/pkg/filter/fields/fields_windows.go b/pkg/filter/fields/fields_windows.go deleted file mode 100644 index 5743682ce..000000000 --- a/pkg/filter/fields/fields_windows.go +++ /dev/null @@ -1,1304 +0,0 @@ -/* - * Copyright 2019-2020 by Nedim Sabic Sabic - * https://www.fibratus.io - * All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package fields - -import ( - "strings" - "unicode" - - "github.com/rabbitstack/fibratus/pkg/event/params" -) - -// Field represents the type alias for the field -type Field string - -const ( - // PsPid represents the process id field - PsPid Field = "ps.pid" - // PsPpid represents the parent process id field - PsPpid Field = "ps.ppid" - // PsName represents the process name field - PsName Field = "ps.name" - // PsComm represents the process command line field. Deprecated. - PsComm Field = "ps.comm" - // PsCmdline represents the process command line field - PsCmdline Field = "ps.cmdline" - // PsExe represents the process image path field - PsExe Field = "ps.exe" - // PsArgs represents the process command line arguments - PsArgs Field = "ps.args" - // PsCwd represents the process current working directory - PsCwd Field = "ps.cwd" - // PsSID represents the process security identifier - PsSID Field = "ps.sid" - // PsDomain represents the process domain field - PsDomain Field = "ps.domain" - // PsUsername represents the process username field - PsUsername Field = "ps.username" - // PsSessionID represents the session id bound to the process - PsSessionID Field = "ps.sessionid" - // PsEnvs represents the process environment variables - PsEnvs Field = "ps.envs" - // PsHandleNames represents the process handles - PsHandleNames Field = "ps.handles" - // PsHandleTypes represents the process handle types - PsHandleTypes Field = "ps.handle.types" - // PsDTB represents the process directory table base address - PsDTB Field = "ps.dtb" - // PsModuleNames represents the process module file names - PsModuleNames Field = "ps.modules" - // PsParentPid represents the parent process identifier field - PsParentPid Field = "ps.parent.pid" - // PsParentName represents the parent process name field - PsParentName Field = "ps.parent.name" - // PsParentComm represents the parent process command line field. Deprecated - PsParentComm Field = "ps.parent.comm" - // PsParentCmdline represents the parent process command line field - PsParentCmdline Field = "ps.parent.cmdline" - // PsParentExe represents the parent process image path field - PsParentExe Field = "ps.parent.exe" - // PsParentArgs represents the parent process command line arguments field - PsParentArgs Field = "ps.parent.args" - // PsParentCwd represents the parent process current working directory field - PsParentCwd Field = "ps.parent.cwd" - // PsParentSID represents the parent process security identifier field - PsParentSID Field = "ps.parent.sid" - // PsParentUsername represents the parent process username field - PsParentUsername Field = "ps.parent.username" - // PsParentDomain represents the parent process domain field - PsParentDomain Field = "ps.parent.domain" - // PsParentSessionID represents the session id field bound to the parent process - PsParentSessionID Field = "ps.parent.sessionid" - // PsParentEnvs represents the parent process environment variables field - PsParentEnvs Field = "ps.parent.envs" - // PsParentHandles represents the parent process handles field - PsParentHandles Field = "ps.parent.handles" - // PsParentHandleTypes represents the parent process handle types field - PsParentHandleTypes Field = "ps.parent.handle.types" - // PsParentDTB represents the parent process directory table base address field - PsParentDTB Field = "ps.parent.dtb" - // PsAncestor represents the process ancestor field - PsAncestor Field = "ps.ancestor" - // PsAccessMask represents the process access rights field - PsAccessMask Field = "ps.access.mask" - // PsAccessMaskNames represents the process access rights list field - PsAccessMaskNames Field = "ps.access.mask.names" - // PsAccessStatus represents the process access status field - PsAccessStatus Field = "ps.access.status" - // PsIsWOW64Field represents the field that indicates if the 32-bit process is created in 64-bit Windows system - PsIsWOW64Field Field = "ps.is_wow64" - // PsIsPackagedField represents the field that indicates if a process is packaged with the MSIX technology - PsIsPackagedField Field = "ps.is_packaged" - // PsIsProtectedField represents the field that indicates if the process is to be run as a protected process - PsIsProtectedField Field = "ps.is_protected" - // PsParentIsWOW64Field represents the field that indicates if the 32-bit process is created in 64-bit Windows system - PsParentIsWOW64Field Field = "ps.parent.is_wow64" - // PsParentIsPackagedField represents the field that indicates if a process is packaged with the MSIX technology - PsParentIsPackagedField Field = "ps.parent.is_packaged" - // PsParentIsProtectedField represents the field that indicates if the process is to be run as a protected process - PsParentIsProtectedField Field = "ps.parent.is_protected" - // PsUUID represents the unique process identifier - PsUUID Field = "ps.uuid" - // PsParentUUID represents the unique parent process identifier - PsParentUUID Field = "ps.parent.uuid" - // PsTokenIntegrityLevel represents the field that indicates the current process integrity level - PsTokenIntegrityLevel = "ps.token.integrity_level" - // PsTokenIsElevated represents the field that indicates if the current process token is elevated - PsTokenIsElevated = "ps.token.is_elevated" - // PsTokenElevationType represents the field that indicates if the current process token elevation type - PsTokenElevationType = "ps.token.elevation_type" - // PsParentTokenIntegrityLevel represents the field that indicates the parent process integrity level - PsParentTokenIntegrityLevel = "ps.parent.token.integrity_level" - // PsParentTokenIsElevated represents the field that indicates if the parent process token is elevated - PsParentTokenIsElevated = "ps.parent.token.is_elevated" - // PsTokenElevationType represents the field that indicates if the parent process token elevation type - PsParentTokenElevationType = "ps.parent.token.elevation_type" - // PsSignatureExists is the field which indicates if the binary is signed, either by embedded or catalog signature - PsSignatureExists Field = "ps.signature.exists" - // PsSignatureTrusted is the field which indicates if the binary signature is trusted - PsSignatureTrusted Field = "ps.signature.trusted" - // PsSignatureIssuer is the field which indicates the certificate issuer - PsSignatureIssuer Field = "ps.signature.issuer" - // PsSignatureSubject is the field which indicates the certificate subject - PsSignatureSubject Field = "ps.signature.subject" - // PsSignatureSerial is the field which indicates the certificate serial - PsSignatureSerial Field = "ps.signature.serial" - // PsSignatureAfter is the field which indicates the timestamp after certificate is no longer valid - PsSignatureAfter Field = "ps.signature.after" - // PsSignatureBefore is the field which indicates the timestamp of the certificate enrollment date - PsSignatureBefore Field = "ps.signature.before" - - // PsPeNumSections represents the number of sections - PsPeNumSections Field = "ps.pe.nsections" - // PsPeNumSymbols represents the number of exported symbols - PsPeNumSymbols Field = "ps.pe.nsymbols" - // PsPeSymbols represents imported symbols - PsPeSymbols Field = "ps.pe.symbols" - // PeImports represents imported libraries (e.g. kernel32.dll) - PsPeImports Field = "ps.pe.imports" - // PeTimestamp is the PE build timestamp - PsPeTimestamp Field = "ps.pe.timestamp" - // PeBaseAddress represents the base address when the binary is loaded - PsPeBaseAddress Field = "ps.pe.address.base" - // PeEntrypoint is the address of the entrypoint function - PsPeEntrypoint Field = "ps.pe.address.entrypoint" - // PeResources represents PE resources - PsPeResources Field = "ps.pe.resources" - // PeCompany represents the company name resource - PsPeCompany Field = "ps.pe.company" - // PeDescription represents the internal description of the file - PsPeDescription Field = "ps.pe.description" - // PeFileVersion represents the internal file version - PsPeFileVersion Field = "ps.pe.file.version" - // PeFileName represents the original file name provided at compile-time. - PsPeFileName Field = "ps.pe.file.name" - // PeCopyright represents the copyright notice emitted at compile-time - PsPeCopyright Field = "ps.pe.copyright" - // PeProduct represents the product name provided at compile-time - PsPeProduct Field = "ps.pe.product" - // PeProductVersion represents the internal product version provided at compile-time - PsPeProductVersion Field = "ps.pe.product.version" - // PeAnomalies represents the field that contains PE anomalies detected during parsing - PsPeAnomalies Field = "ps.pe.anomalies" - // PsPeImphash is the field that yields the PE import hash - PsPeImphash Field = "ps.pe.imphash" - // PsPeIsDotnet is the field which indicates if the binary contains the .NET assembly - PsPeIsDotnet Field = "ps.pe.is_dotnet" - // PsPeIsModified is the field that indicates whether disk and in-memory PE headers differ - PsPeIsModified Field = "ps.pe.is_modified" - - // ThreadBasePrio is the base thread priority - ThreadBasePrio Field = "thread.prio" - // ThreadIOPrio is the thread I/O priority - ThreadIOPrio Field = "thread.io.prio" - // ThreadPagePrio is the thread page priority - ThreadPagePrio Field = "thread.page.prio" - // ThreadKstackBase is the thread kernel stack start address - ThreadKstackBase Field = "thread.kstack.base" - // ThreadKstackLimit is the thread kernel stack end address - ThreadKstackLimit Field = "thread.kstack.limit" - // ThreadUstackBase is the thread user stack start address - ThreadUstackBase Field = "thread.ustack.base" - // ThreadUstackLimit is the thead user stack end address - ThreadUstackLimit Field = "thread.ustack.limit" - // ThreadEntrypoint is the thread entrypoint address - ThreadEntrypoint Field = "thread.entrypoint" - // ThreadStartAddress is the thread start address - ThreadStartAddress Field = "thread.start_address" - // ThreadPID is the process identifier where the thread is created - ThreadPID Field = "thread.pid" - // ThreadTEB is the thread environment block base address - ThreadTEB Field = "thread.teb_address" - // ThreadAccessMask represents the thread access rights field - ThreadAccessMask Field = "thread.access.mask" - // ThreadAccessMaskNames represents the thread access rights list field - ThreadAccessMaskNames Field = "thread.access.mask.names" - // ThreadAccessStatus represents the thread access status field - ThreadAccessStatus Field = "thread.access.status" - // ThreadCallstackSummary represents the thread callstack summary field - ThreadCallstackSummary Field = "thread.callstack.summary" - // ThreadCallstackKernelSummary represents the kernel thread callstack summary field - ThreadCallstackKernelSummary Field = "thread.callstack.kernel_summary" - // ThreadCallstackDetail represents the thread callstack detail field - ThreadCallstackDetail Field = "thread.callstack.detail" - // ThreadCallstackModules represents the callstack modules field - ThreadCallstackModules Field = "thread.callstack.modules" - // ThreadCallstackSymbols represents the callstack symbols field - ThreadCallstackSymbols Field = "thread.callstack.symbols" - // ThreadCallstackProtections represents the callstack region protections field - ThreadCallstackProtections Field = "thread.callstack.protections" - // ThreadCallstackAllocationSizes represents the private region page sizes field - ThreadCallstackAllocationSizes Field = "thread.callstack.allocation_sizes" - // ThreadCallstackCallsiteLeadingAssembly represents the callsite prelude opcodes field - ThreadCallstackCallsiteLeadingAssembly Field = "thread.callstack.callsite_leading_assembly" - // ThreadCallstackCallsiteTrailingAssembly represents the callsite postlude opcodes field - ThreadCallstackCallsiteTrailingAssembly Field = "thread.callstack.callsite_trailing_assembly" - // ThreadCallstackIsUnbacked represents the field that indicates if there is an unbacked stack frame - ThreadCallstackIsUnbacked Field = "thread.callstack.is_unbacked" - // ThreadStartAddressSymbol represents the symbol corresponding to the thread start address - ThreadStartAddressSymbol Field = "thread.start_address.symbol" - // ThreadStartAddressModule represents the module corresponding to the thread start address - ThreadStartAddressModule Field = "thread.start_address.module" - // ThreadCallstackAddresses represents the all callstack return addresses - ThreadCallstackAddresses Field = "thread.callstack.addresses" - // ThreadCallstackFinalUserModuleName represents the final user space stack frame module name - ThreadCallstackFinalUserModuleName Field = "thread.callstack.final_user_module.name" - // ThreadCallstackFinalUserModulePath represents the final user space stack frame module path - ThreadCallstackFinalUserModulePath Field = "thread.callstack.final_user_module.path" - // ThreadCallstackFinalUserSymbolName represents the final user space stack frame symbol name - ThreadCallstackFinalUserSymbolName Field = "thread.callstack.final_user_symbol.name" - // ThreadCallstackFinalKernelModuleName represents the final kernel space stack frame module name - ThreadCallstackFinalKernelModuleName Field = "thread.callstack.final_kernel_module.name" - // ThreadCallstackFinalKernelModulePath represents the final kernel space stack frame module name - ThreadCallstackFinalKernelModulePath Field = "thread.callstack.final_kernel_module.path" - // ThreadCallstackFinalKernelSymbolName represents the final kernel space stack frame symbol name - ThreadCallstackFinalKernelSymbolName Field = "thread.callstack.final_kernel_symbol.name" - // ThreadCallstackFinalUserModuleSignatureExists represents the signature status of the final user space stack frame module - ThreadCallstackFinalUserModuleSignatureExists Field = "thread.callstack.final_user_module.signature.exists" - // ThreadCallstackFinalUserModuleSignatureTrusted represents the trust status of the final user space stack frame module signature - ThreadCallstackFinalUserModuleSignatureTrusted Field = "thread.callstack.final_user_module.signature.trusted" - // ThreadCallstackFinalUserModuleSignatureIssuer represents the final user space stack frame module certificate issuer - ThreadCallstackFinalUserModuleSignatureIssuer Field = "thread.callstack.final_user_module.signature.issuer" - // ThreadCallstackFinalUserModuleSignatureSubject represents the final user space stack frame module certificate subject - ThreadCallstackFinalUserModuleSignatureSubject Field = "thread.callstack.final_user_module.signature.subject" - - // PeNumSections represents the number of sections - PeNumSections Field = "pe.nsections" - // PeNumSymbols represents the number of exported symbols - PeNumSymbols Field = "pe.nsymbols" - // PeSymbols represents imported symbols - PeSymbols Field = "pe.symbols" - // PeImports represents imported libraries (e.g. kernel32.dll) - PeImports Field = "pe.imports" - // PeTimestamp is the PE build timestamp - PeTimestamp Field = "pe.timestamp" - // PeBaseAddress represents the base address when the binary is loaded - PeBaseAddress Field = "pe.address.base" - // PeEntrypoint is the address of the entrypoint function - PeEntrypoint Field = "pe.address.entrypoint" - // PeResources represents PE resources - PeResources Field = "pe.resources" - // PeCompany represents the company name resource - PeCompany Field = "pe.company" - // PeDescription represents the internal description of the file - PeDescription Field = "pe.description" - // PeFileVersion represents the internal file version - PeFileVersion Field = "pe.file.version" - // PeFileName represents the original file name provided at compile-time. - PeFileName Field = "pe.file.name" - // PeCopyright represents the copyright notice emitted at compile-time - PeCopyright Field = "pe.copyright" - // PeProduct represents the product name provided at compile-time - PeProduct Field = "pe.product" - // PeProductVersion represents the internal product version provided at compile-time - PeProductVersion Field = "pe.product.version" - // PeIsDLL indicates if the file is a DLL - PeIsDLL Field = "pe.is_dll" - // PeIsDriver indicates if the file is a driver - PeIsDriver Field = "pe.is_driver" - // PeIsExecutable indicates if the file is an executable - PeIsExecutable Field = "pe.is_exec" - // PeAnomalies represents the field that contains PE anomalies detected during parsing - PeAnomalies Field = "pe.anomalies" - // PeImphash is the field that yields the PE import hash - PeImphash Field = "pe.imphash" - // PeIsDotnet is the field which indicates if the binary contains the .NET assembly - PeIsDotnet Field = "pe.is_dotnet" - // PeIsSigned is the field which indicates if the binary is signed, either by embedded or catalog signature - PeIsSigned Field = "pe.is_signed" - // PeIsTrusted is the field which indicates if the binary signature is trusted - PeIsTrusted Field = "pe.is_trusted" - // PeCertIssuer is the field which indicates the certificate issuer - PeCertIssuer Field = "pe.cert.issuer" - // PeCertSubject is the field which indicates the certificate subject - PeCertSubject Field = "pe.cert.subject" - // PeCertSerial is the field which indicates the certificate serial - PeCertSerial Field = "pe.cert.serial" - // PeCertAfter is the field which indicates the timestamp after certificate is no longer valid - PeCertAfter Field = "pe.cert.after" - // PeCertBefore is the field which indicates the timestamp of the certificate enrollment date - PeCertBefore Field = "pe.cert.before" - // PeIsModified is the field that indicates whether disk and in-memory PE headers differ - PeIsModified Field = "pe.is_modified" - - // EvtSeq is the event sequence number - EvtSeq Field = "evt.seq" - // EvtPID is the process identifier that generated the event - EvtPID Field = "evt.pid" - // EvtTID is the thread identifier that generated the event - EvtTID Field = "evt.tid" - // EvtCPU is the CPU core where the event was generated - EvtCPU Field = "evt.cpu" - // EvtDesc represents the event description - EvtDesc Field = "evt.desc" - // EvtHost represents the host where the event was produced - EvtHost Field = "evt.host" - // EvtTime is the event time - EvtTime Field = "evt.time" - // EvtTimeHour is the hour part of the event time - EvtTimeHour Field = "evt.time.h" - // EvtTimeMin is the minute part of the event time - EvtTimeMin Field = "evt.time.m" - // EvtTimeSec is the second part of the event time - EvtTimeSec Field = "evt.time.s" - // EvtTimeNs is the nanosecond part of the event time - EvtTimeNs Field = "evt.time.ns" - // EvtDate is the event date - EvtDate Field = "evt.date" - // EvtDateDay is the day of event date - EvtDateDay Field = "evt.date.d" - // EvtDateMonth is the month of event date - EvtDateMonth Field = "evt.date.m" - // EvtDateYear is the year of event date - EvtDateYear Field = "evt.date.y" - // EvtDateTz is the time zone of event timestamp - EvtDateTz Field = "evt.date.tz" - // EvtDateWeek is the event week number - EvtDateWeek Field = "evt.date.week" - // EvtDateWeekday is the event week day - EvtDateWeekday Field = "evt.date.weekday" - // EvtName is the event name - EvtName Field = "evt.name" - // EvtCategory is the event category - EvtCategory Field = "evt.category" - // EvtNparams is the number of event parameters - EvtNparams Field = "evt.nparams" - // EvtArg represents the field sequence for generic argument access - EvtArg Field = "evt.arg" - // EvtIsDirectSyscall represents the field that designates if this event is - // performing a direct syscall. - EvtIsDirectSyscall Field = "evt.is_direct_syscall" - // EvtIsIndirectSyscall represents the field that designates if this event is - // performing an indirect syscall. - EvtIsIndirectSyscall Field = "evt.is_indirect_syscall" - - // KevtSeq is the event sequence number - KevtSeq Field = "kevt.seq" - // KevtPID is the process identifier that generated the event - KevtPID Field = "kevt.pid" - // KevtTID is the thread identifier that generated the event - KevtTID Field = "kevt.tid" - // KevtCPU is the CPU core where the event was generated - KevtCPU Field = "kevt.cpu" - // KevtDesc represents the event description - KevtDesc Field = "kevt.desc" - // KevtHost represents the host where the event was produced - KevtHost Field = "kevt.host" - // KevtTime is the event time - KevtTime Field = "kevt.time" - // KevtTimeHour is the hour part of the event time - KevtTimeHour Field = "kevt.time.h" - // KevtTimeMin is the minute part of the event time - KevtTimeMin Field = "kevt.time.m" - // KevtTimeSec is the second part of the event time - KevtTimeSec Field = "kevt.time.s" - // KevtTimeNs is the nanosecond part of the event time - KevtTimeNs Field = "kevt.time.ns" - // KevtDate is the event date - KevtDate Field = "kevt.date" - // KevtDateDay is the day of event date - KevtDateDay Field = "kevt.date.d" - // KevtDateMonth is the month of event date - KevtDateMonth Field = "kevt.date.m" - // KevtDateYear is the year of event date - KevtDateYear Field = "kevt.date.y" - // KevtDateTz is the time zone of event timestamp - KevtDateTz Field = "kevt.date.tz" - // KevtDateWeek is the event week number - KevtDateWeek Field = "kevt.date.week" - // KevtDateWeekday is the event week day - KevtDateWeekday Field = "kevt.date.weekday" - // KevtName is the event name - KevtName Field = "kevt.name" - // KevtCategory is the event category - KevtCategory Field = "kevt.category" - // KevtNparams is the number of event parameters - KevtNparams Field = "kevt.nparams" - // KevtArg represents the field sequence for generic argument access - KevtArg Field = "kevt.arg" - - // HandleID represents the handle identifier within the process address space - HandleID Field = "handle.id" - // HandleObject represents the handle object address - HandleObject Field = "handle.object" - // HandleName represents the handle name - HandleName Field = "handle.name" - // HandleType represents the handle type (e.g. file) - HandleType Field = "handle.type" - - // NetDIP represents network destination IP address - NetDIP Field = "net.dip" - // NetSIP represents the source IP address - NetSIP Field = "net.sip" - // NetDport represents the destination port - NetDport Field = "net.dport" - // NetSport represents the source port - NetSport Field = "net.sport" - // NetDportName represents the destination port IANA name - NetDportName Field = "net.dport.name" - // NetSportName represents the source port IANA name - NetSportName Field = "net.sport.name" - // NetL4Proto represents the Layer4 protocol name (e.g. TCP) - NetL4Proto Field = "net.l4.proto" - // NetPacketSize represents the packet size - NetPacketSize Field = "net.size" - // NetSIPNames represents the source IP names - NetSIPNames Field = "net.sip.names" - // NetDIPNames represents the destination IP names - NetDIPNames Field = "net.dip.names" - - // FileObject represents the address of the file object - FileObject Field = "file.object" - // FileName represents the file base name (e.g. cmd.exe) - FileName Field = "file.name" - // FilePath represents the file full path (e.g. C:\Windows\System32\cmd.exe) - FilePath Field = "file.path" - // FilePathStem represents the full file path without extension (e.g. C:\Windows\System32\cmd) - FilePathStem Field = "file.path.stem" - // FileExtension represents the file extension (e.g. .exe or .dll) - FileExtension Field = "file.extension" - // FileOperation represents the file operation (e.g. create) - FileOperation Field = "file.operation" - // FileShareMask represents the file share mask - FileShareMask Field = "file.share.mask" - // FileShareMode represents the file share mode field - FileShareMode Field = "file.share_mode" - // FileIOSize represents the number of read/written bytes - FileIOSize Field = "file.io.size" - // FileOffset represents the read/write offset - FileOffset Field = "file.offset" - // FileType represents the file type - FileType Field = "file.type" - // FileAttributes represents a slice of file attributes - FileAttributes Field = "file.attributes" - // FileStatus represents the status message of the file operation - FileStatus Field = "file.status" - // FileViewBase represents the base address of the mapped view - FileViewBase Field = "file.view.base" - // FileViewSize represents the size of the mapped view - FileViewSize Field = "file.view.size" - // FileViewType represents the type of the mapped view section - FileViewType Field = "file.view.type" - // FileViewProtection represents the protection attributes of the section view - FileViewProtection Field = "file.view.protection" - // FileIsDLL indicates if the created file is a DLL - FileIsDLL Field = "file.is_dll" - // FileIsDriver indicates if the created file is a driver - FileIsDriver Field = "file.is_driver" - // FileIsExecutable indicates if the created file is an executable - FileIsExecutable Field = "file.is_exec" - // FilePID represents the field that denotes the process id performing file operations - FilePID Field = "file.pid" - // FileKey represents the field that uniquely identifies the file object. - FileKey Field = "file.key" - // FileInfoClass represents the field that identifies the file information class - FileInfoClass Field = "file.info_class" - // FileInfoAllocationSize represents the field that contains the file allocation size - FileInfoAllocationSize Field = "file.info.allocation_size" - // FileInfoEOFSize represents the field that contains the EOF size - FileInfoEOFSize Field = "file.info.eof_size" - // FileInfoIsDispositionDeleteFile represents the field that indicates if the file is deleted when its handle is closed - FileInfoIsDispositionDeleteFile Field = "file.info.is_disposition_delete_file" - - // RegistryPath represents the full registry path - RegistryPath Field = "registry.path" - // RegistryKeyName represents the registry key name - RegistryKeyName Field = "registry.key.name" - // RegistryKCB represents the registry KCB address - RegistryKCB Field = "registry.kcb" - // RegistryValue represents the registry value name field - RegistryValue Field = "registry.value" - // RegistryValueType represents the registry value type field - RegistryValueType Field = "registry.value.type" - // RegistryData represents the captured registry data field - RegistryData Field = "registry.data" - // RegistryStatus represent the registry operation status - RegistryStatus Field = "registry.status" - - // ImageBase is the module base address - ImageBase Field = "image.base.address" - // ImageSize is the module size - ImageSize Field = "image.size" - // ImageChecksum represents the module checksum hash - ImageChecksum Field = "image.checksum" - // ImageDefaultAddress represents the module address - ImageDefaultAddress Field = "image.default.address" - // ImagePath is the module full path - ImagePath Field = "image.path" - // ImageName is the module name - ImageName Field = "image.name" - // ImagePID is the pid of the process where the image was loaded - ImagePID Field = "image.pid" - // ImageSignatureType represents the image signature type - ImageSignatureType Field = "image.signature.type" - // ImageSignatureLevel represents the image signature level - ImageSignatureLevel Field = "image.signature.level" - // ImageCertSubject is the field that indicates the subject of the certificate is the entity its public key is associated with. - ImageCertSubject = "image.cert.subject" - // ImageCertIssuer is the field that represents the certificate authority (CA). - ImageCertIssuer = "image.cert.issuer" - // ImageCertSerial is the field that represents the serial number MUST be a positive integer assigned - // by the CA to each certificate. - ImageCertSerial = "image.cert.serial" - // ImageCertBefore is the field that specifies the certificate won't be valid before this timestamp. - ImageCertBefore = "image.cert.before" - // ImageCertAfter is the field that specifies the certificate won't be valid after this timestamp. - ImageCertAfter = "image.cert.after" - // ImageIsDLL indicates if the loaded image is a DLL - ImageIsDLL Field = "image.is_dll" - // ImageIsDriver indicates if the loaded image is a driver - ImageIsDriver Field = "image.is_driver" - // ImageIsExecutable indicates if the loaded image is an executable - ImageIsExecutable Field = "image.is_exec" - // ImageIsDotnet indicates if the loaded image is a .NET assembly - ImageIsDotnet Field = "image.is_dotnet" - - // DllBase is the DLL base address - DllBase Field = "dll.base" - // DllSize is the DLL virtual mapped space size - DllSize Field = "dll.size" - // DllPath is the DLL full path - DllPath Field = "dll.path" - // DllPath is the DLL path stem field - DllPathStem Field = "dll.path.stem" - // DllName is the DLL name - DllName Field = "dll.name" - // DllPID is the pid of the process where the DLL was loaded - DllPID Field = "dll.pid" - // DllSignatureType represents the DLL signature type - DllSignatureType Field = "dll.signature.type" - // DllSignatureLevel represents the DLL signature level - DllSignatureLevel Field = "dll.signature.level" - // DllSignatureExists is the field that determines if the DLL signature exists - DllSignatureExists Field = "dll.signature.exists" - // DllSignatureTrusted is the filed that determines if the DLL signature is trusted - DllSignatureTrusted Field = "dll.signature.trusted" - // DllSignatureSubject is the field that indicates the subject of the certificate is the entity its public key is associated with. - DllSignatureSubject = "dll.signature.subject" - // DllSignatureIssuer is the field that represents the certificate authority (CA). - DllSignatureIssuer = "dll.signature.issuer" - // DllSignatureSerial is the field that represents the serial number MUST be a positive integer assigned - // by the CA to each certificate. - DllSignatureSerial = "dll.signature.serial" - // DllSignatureBefore is the field that specifies the certificate won't be valid before this timestamp. - DllSignatureBefore = "dll.signature.before" - // DllSignatureAfter is the field that specifies the certificate won't be valid after this timestamp. - DllSignatureAfter = "dll.signature.after" - // DllIsDotnet indicates if the DLL is a .NET assembly. - DllIsDotnet Field = "dll.pe.is_dotnet" - - // ModuleBase is the module base address - ModuleBase Field = "module.base" - // ModuleSize is the module size - ModuleSize Field = "module.size" - // ModuleChecksum represents the module checksum hash - ModuleChecksum Field = "module.checksum" - // ModuleDefaultAddress represents the module address - ModuleDefaultAddress Field = "module.default_address" - // ModulePath is the module full path - ModulePath Field = "module.path" - // ModulePathStem is the module path stem field - ModulePathStem Field = "module.path.stem" - // ModuleName is the module name - ModuleName Field = "module.name" - // ModulePID is the pid of the process where the module was loaded - ModulePID Field = "module.pid" - // ModuleSignatureType represents the module signature type - ModuleSignatureType Field = "module.signature.type" - // ModuleSignatureLevel represents the module signature level - ModuleSignatureLevel Field = "module.signature.level" - // ModuleSignatureExists is the field that determines if the module signature exists - ModuleSignatureExists Field = "module.signature.exists" - // ModuleSignatureTrusted is the filed that determines if the module signature is trusted - ModuleSignatureTrusted Field = "module.signature.trusted" - // ModuleSignatureSubject is the field that indicates the subject of the certificate is the entity its public key is associated with. - ModuleSignatureSubject = "module.signature.subject" - // ModuleSignatureIssuer is the field that represents the certificate authority (CA). - ModuleSignatureIssuer = "module.signature.issuer" - // ModuleSignatureSerial is the field that represents the serial number MUST be a positive integer assigned - // by the CA to each certificate. - ModuleSignatureSerial = "module.signature.serial" - // ModuleSignatureBefore is the field that specifies the certificate won't be valid before this timestamp. - ModuleSignatureBefore = "module.signature.before" - // ModuleSignatureAfter is the field that specifies the certificate won't be valid after this timestamp. - ModuleSignatureAfter = "module.signature.after" - // ModuleIsDLL indicates if the loaded module is a DLL - ModuleIsDLL Field = "module.is_dll" - // ModuleIsDriver indicates if the loaded module is a driver - ModuleIsDriver Field = "module.is_driver" - // ModuleIsExecutable indicates if the loaded module is an executable - ModuleIsExecutable Field = "module.is_exec" - // ModuleIsDotnet indicates if the loaded module is a .NET assembly - ModuleIsDotnet Field = "module.pe.is_dotnet" - - // MemBaseAddress identifies the field that denotes the allocation base address - MemBaseAddress Field = "mem.address" - // MemRegionSize Field identifies the field that represents the allocated region size - MemRegionSize Field = "mem.size" - // MemAllocType identifies the field that represents region allocation type - MemAllocType Field = "mem.alloc" - // MemPageType identifies the parameter that represents the allocated region type - MemPageType Field = "mem.type" - // MemProtection identifies the field that represents the memory protection for the range of pages - MemProtection Field = "mem.protection" - // MemProtectionMask identifies the field that represents the memory protection in mask notation - MemProtectionMask Field = "mem.protection.mask" - - // DNSName identifies the field that represents the DNS name - DNSName Field = "dns.name" - // DNSRR identifies the field that represents the DNS record type - DNSRR Field = "dns.rr" - // DNSOptions identifies the field that represents the DNS options - DNSOptions Field = "dns.options" - // DNSAnswers identifies the field that represents the DNS answers - DNSAnswers Field = "dns.answers" - // DNSRcode identifies the field that represents the DNS response code - DNSRcode Field = "dns.rcode" - - // ThreadpoolPoolID identifies the field that represents the thread pool identifier - ThreadpoolPoolID = "threadpool.id" - // ThreadpoolTaskID identifies the field that represents the thread pool task identifier - ThreadpoolTaskID = "threadpool.task.id" - // ThreadpoolCallbackAddress identifies the field that represents the address of the callback function - ThreadpoolCallbackAddress = "threadpool.callback.address" - // ThreadpoolCallbackSymbol identifies the field that represents the callback symbol - ThreadpoolCallbackSymbol = "threadpool.callback.symbol" - // ThreadpoolCallbackModule identifies the field that represents the module containing the callback symbol - ThreadpoolCallbackModule = "threadpool.callback.module" - // ThreadpoolCallbackContext identifies the field that represents the address of the callback context - ThreadpoolCallbackContext = "threadpool.callback.context" - // ThreadpoolCallbackContextRip identifies the field that represents the value of instruction pointer contained in the callback context - ThreadpoolCallbackContextRip = "threadpool.callback.context.rip" - // ThreadpoolCallbackContextRipSymbol identifies the field that represents the symbol name associated with the instruction pointer in callback context - ThreadpoolCallbackContextRipSymbol = "threadpool.callback.context.rip.symbol" - // ThreadpoolCallbackContextRipModule identifies the field that represents the module name associated with the instruction pointer in callback context - ThreadpoolCallbackContextRipModule = "threadpool.callback.context.rip.module" - // ThreadpoolSubprocessTag identifies the field that represents the service identifier associated with the thread pool - ThreadpoolSubprocessTag = "threadpool.subprocess_tag" - // ThreadpoolTimerDuetime identifies the field that represents the timer due time - ThreadpoolTimerDuetime = "threadpool.timer.duetime" - // ThreadpoolTimerSubqueue identifies the field that represents the memory address of the timer subqueue - ThreadpoolTimerSubqueue = "threadpool.timer.subqueue" - // ThreadpoolTimer identifies the field that represents the memory address of the timer object - ThreadpoolTimer = "threadpool.timer.address" - // ThreadpoolTimerPeriod identifies the field that represents the period of the timer - ThreadpoolTimerPeriod = "threadpool.timer.period" - // ThreadpoolTimerWindow identifies the field that represents the timer tolerate period - ThreadpoolTimerWindow = "threadpool.timer.window" - // ThreadpoolTimerAbsolute identifies the field that indicates if the timer is absolute or relative - ThreadpoolTimerAbsolute = "threadpool.timer.is_absolute" -) - -// String casts the field type to string. -func (f Field) String() string { return string(f) } - -// Type returns the data type that this field contains. -func (f Field) Type() params.Type { return fields[f].Type } - -func (f Field) IsPsField() bool { return strings.HasPrefix(string(f), "ps.") } -func (f Field) IsKevtField() bool { return strings.HasPrefix(string(f), "kevt.") } -func (f Field) IsEvtField() bool { return strings.HasPrefix(string(f), "evt.") } -func (f Field) IsThreadField() bool { return strings.HasPrefix(string(f), "thread.") } -func (f Field) IsImageField() bool { return strings.HasPrefix(string(f), "image.") } -func (f Field) IsFileField() bool { return strings.HasPrefix(string(f), "file.") } -func (f Field) IsRegistryField() bool { return strings.HasPrefix(string(f), "registry.") } -func (f Field) IsNetworkField() bool { return strings.HasPrefix(string(f), "net.") } -func (f Field) IsHandleField() bool { return strings.HasPrefix(string(f), "handle.") } -func (f Field) IsPeField() bool { - return strings.HasPrefix(string(f), "pe.") || strings.HasPrefix(string(f), "ps.pe.") || strings.HasPrefix(string(f), "ps.signature.") -} -func (f Field) IsModuleField() bool { - return strings.HasPrefix(string(f), "module.") || strings.HasPrefix(string(f), "dll.") -} -func (f Field) IsMemField() bool { return strings.HasPrefix(string(f), "mem.") } -func (f Field) IsDNSField() bool { return strings.HasPrefix(string(f), "dns.") } -func (f Field) IsThreadpoolField() bool { return strings.HasPrefix(string(f), "threadpool.") } - -func (f Field) IsPeSection() bool { return f == PeNumSections || f == PsPeNumSections } -func (f Field) IsPeSymbol() bool { - return f == PeSymbols || f == PeNumSymbols || f == PeImports || f == PsPeSymbols || f == PsPeNumSymbols || f == PsPeImports -} -func (f Field) IsPeVersionResource() bool { - return f == PeCompany || f == PeCopyright || f == PeDescription || f == PeFileName || f == PeFileVersion || f == PeProduct || f == PeProductVersion || - f == PsPeCompany || f == PsPeCopyright || f == PsPeDescription || f == PsPeFileName || f == PsPeFileVersion || f == PsPeProduct || f == PsPeProductVersion -} -func (f Field) IsPeVersionResources() bool { return f == PeResources || f == PsPeResources } -func (f Field) IsPeImphash() bool { return f == PeImphash || f == PsPeImphash } -func (f Field) IsPeDotnet() bool { return f == PeIsDotnet || f == PsPeIsDotnet } -func (f Field) IsPeAnomalies() bool { return f == PeAnomalies || f == PsPeAnomalies } -func (f Field) IsPeSignature() bool { - return f == PeIsTrusted || f == PeIsSigned || f == PeCertIssuer || f == PeCertSerial || f == PeCertSubject || f == PeCertBefore || f == PeCertAfter || strings.HasPrefix(string(f), "ps.signature.") -} -func (f Field) IsPeIsTrusted() bool { return f == PeIsTrusted || f == PsSignatureTrusted } -func (f Field) IsPeIsSigned() bool { return f == PeIsSigned || f == PsSignatureExists } - -func (f Field) IsPeCert() bool { - return strings.HasPrefix(string(f), "pe.cert.") || f == PsSignatureIssuer || f == PsSignatureSubject || f == PsSignatureSerial || f == PsSignatureAfter || f == PsSignatureBefore -} -func (f Field) IsImageCert() bool { return strings.HasPrefix(string(f), "image.cert.") } -func (f Field) IsModuleCert() bool { - return f == ModuleSignatureSubject || f == ModuleSignatureIssuer || f == ModuleSignatureSerial || f == ModuleSignatureAfter || f == ModuleSignatureBefore || - f == DllSignatureSubject || f == DllSignatureIssuer || f == DllSignatureSerial || f == DllSignatureAfter || f == DllSignatureBefore -} -func (f Field) IsModuleSignature() bool { - return strings.HasPrefix(string(f), "module.signature.") || strings.HasPrefix(string(f), "dll.signature.") -} - -func (f Field) IsPeModified() bool { return f == PeIsModified || f == PsPeIsModified } - -// Segment represents the type alias for the segment. Segment -// denotes the property anchored to the bound field reference. -// Let's look through an example. $module.name is the literal -// composed of bound field ($module) and the segment (name). -// Segments are most commonly used in the context of bound -// variables in foreach function. -type Segment string - -const ( - PathSegment Segment = "path" - NameSegment Segment = "name" - TypeSegment Segment = "type" - SizeSegment Segment = "size" - ChecksumSegment Segment = "checksum" - AddressSegment Segment = "address" - OffsetSegment Segment = "offset" - EntropySegment Segment = "entropy" - MD5Segment Segment = "md5" - - PIDSegment Segment = "pid" - CmdlineSegment Segment = "cmdline" - ExeSegment Segment = "exe" - ArgsSegment Segment = "args" - CwdSegment Segment = "cwd" - SIDSegment Segment = "sid" - SessionIDSegment Segment = "sessionid" - UsernameSegment Segment = "username" - DomainSegment Segment = "domain" - TokenIntegrityLevelSegment Segment = "token.integrity_level" - TokenIsElevatedSegment Segment = "token.is_elevated" - TokenElevationTypeSegment Segment = "token.elevation_type" - - TidSegment Segment = "tid" - StartAddressSegment Segment = "start_address" - UserStackBaseSegment Segment = "user_stack_base" - UserStackLimitSegment Segment = "user_stack_limit" - KernelStackBaseSegment Segment = "kernel_stack_base" - KernelStackLimitSegment Segment = "kernel_stack_limit" - - SymbolSegment Segment = "symbol" - ModuleSegment Segment = "module" - AllocationSizeSegment Segment = "allocation_size" - ProtectionSegment Segment = "protection" - IsUnbackedSegment Segment = "is_unbacked" - CallsiteLeadingAssemblySegment Segment = "callsite_leading_assembly" - CallsiteTrailingAssemblySegment Segment = "callsite_trailing_assembly" - - ModuleSignatureExistsSegment Segment = "module.signature.exists" - ModuleSignatureTrustedSegment Segment = "module.signature.trusted" - ModuleSignatureIssuerSegment Segment = "module.signature.issuer" - ModuleSignatureSubjectSegment Segment = "module.signature.subject" -) - -var segments = map[Segment]bool{ - NameSegment: true, - PathSegment: true, - TypeSegment: true, - EntropySegment: true, - SizeSegment: true, - MD5Segment: true, - AddressSegment: true, - ChecksumSegment: true, - PIDSegment: true, - CmdlineSegment: true, - ExeSegment: true, - ArgsSegment: true, - CwdSegment: true, - SIDSegment: true, - SessionIDSegment: true, - UsernameSegment: true, - DomainSegment: true, - TokenIntegrityLevelSegment: true, - TokenIsElevatedSegment: true, - TokenElevationTypeSegment: true, - TidSegment: true, - StartAddressSegment: true, - UserStackBaseSegment: true, - UserStackLimitSegment: true, - KernelStackBaseSegment: true, - KernelStackLimitSegment: true, - OffsetSegment: true, - SymbolSegment: true, - ModuleSegment: true, - AllocationSizeSegment: true, - ProtectionSegment: true, - IsUnbackedSegment: true, - CallsiteLeadingAssemblySegment: true, - CallsiteTrailingAssemblySegment: true, - ModuleSignatureExistsSegment: true, - ModuleSignatureTrustedSegment: true, - ModuleSignatureIssuerSegment: true, - ModuleSignatureSubjectSegment: true, -} - -var allowedSegments = map[Field][]Segment{ - PsAncestors: {NameSegment, PIDSegment, CmdlineSegment, ExeSegment, ArgsSegment, CwdSegment, SIDSegment, SessionIDSegment, UsernameSegment, DomainSegment, TokenIntegrityLevelSegment, TokenIsElevatedSegment, TokenElevationTypeSegment}, - PsThreads: {TidSegment, StartAddressSegment, UserStackBaseSegment, UserStackLimitSegment, KernelStackBaseSegment, KernelStackLimitSegment}, - PsModules: {PathSegment, NameSegment, AddressSegment, SizeSegment, ChecksumSegment}, - PsMmaps: {AddressSegment, TypeSegment, SizeSegment, ProtectionSegment, PathSegment}, - PeSections: {NameSegment, SizeSegment, EntropySegment, MD5Segment}, - PsPeSections: {NameSegment, SizeSegment, EntropySegment, MD5Segment}, - ThreadCallstack: {AddressSegment, OffsetSegment, SymbolSegment, ModuleSegment, AllocationSizeSegment, ProtectionSegment, IsUnbackedSegment, CallsiteLeadingAssemblySegment, CallsiteTrailingAssemblySegment, ModuleSignatureExistsSegment, ModuleSignatureTrustedSegment, ModuleSignatureIssuerSegment, ModuleSignatureSubjectSegment}, -} - -func (s Segment) IsEntropy() bool { return s == EntropySegment } - -// IsSegmentAllowed determines if the segment is valid for the pseudo field. -func IsSegmentAllowed(f Field, s Segment) bool { - segs := allowedSegments[f] - if len(segs) == 0 { - return false - } - - for _, seg := range segs { - if seg == s { - return true - } - } - - return false -} - -// SegmentsHint returns the sequence of available segments for the pseudo field. -func SegmentsHint(f Field) string { - segs := allowedSegments[f] - if len(segs) == 0 { - return "" - } - - s := make([]string, len(segs)) - for i, seg := range segs { - s[i] = string(seg) - } - - return strings.Join(s, ", ") -} - -// IsSegment indicates if the given string is recognized as a known segment. -func IsSegment(s string) bool { - return segments[Segment(s)] -} - -// Pseudo fields provide access to the process/event internal state. They -// are typically used in conjunction with the foreach function as its -// first argument. - -var ( - PsModules Field = "ps._modules" - PsThreads Field = "ps._threads" - PsMmaps Field = "ps._mmaps" - PsAncestors Field = "ps._ancestors" - PsPeSections Field = "ps.pe._sections" - ThreadCallstack Field = "thread._callstack" - PeSections Field = "pe._sections" -) - -func IsPseudoField(f Field) bool { - return f == PsAncestors || f == PsModules || f == PsThreads || f == PsMmaps || f == ThreadCallstack || f == PeSections || f == PsPeSections -} - -func (f Field) IsPeSectionsPseudo() bool { return f == PeSections || f == PsPeSections } - -var fields = map[Field]FieldInfo{ - EvtSeq: {EvtSeq, "event sequence number", params.Uint64, []string{"evt.seq > 666"}, nil, nil}, - EvtPID: {EvtPID, "process identifier generating the event", params.Uint32, []string{"evt.pid = 6"}, nil, nil}, - EvtTID: {EvtTID, "thread identifier generating the event", params.Uint32, []string{"evt.tid = 1024"}, nil, nil}, - EvtCPU: {EvtCPU, "logical processor core where the event was generated", params.Uint8, []string{"evt.cpu = 2"}, nil, nil}, - EvtName: {EvtName, "symbolical event name", params.AnsiString, []string{"evt.name = 'CreateThread'"}, nil, nil}, - EvtCategory: {EvtCategory, "event category", params.AnsiString, []string{"evt.category = 'registry'"}, nil, nil}, - EvtDesc: {EvtDesc, "event description", params.AnsiString, []string{"evt.desc contains 'Creates a new process'"}, nil, nil}, - EvtHost: {EvtHost, "host name on which the event was produced", params.UnicodeString, []string{"evt.host contains 'kitty'"}, nil, nil}, - EvtTime: {EvtTime, "event timestamp as a time string", params.Time, []string{"evt.time = '17:05:32'"}, nil, nil}, - EvtTimeHour: {EvtTimeHour, "hour within the day on which the event occurred", params.Time, []string{"evt.time.h = 23"}, nil, nil}, - EvtTimeMin: {EvtTimeMin, "minute offset within the hour on which the event occurred", params.Time, []string{"evt.time.m = 54"}, nil, nil}, - EvtTimeSec: {EvtTimeSec, "second offset within the minute on which the event occurred", params.Time, []string{"evt.time.s = 0"}, nil, nil}, - EvtTimeNs: {EvtTimeNs, "nanoseconds specified by event timestamp", params.Int64, []string{"evt.time.ns > 1591191629102337000"}, nil, nil}, - EvtDate: {EvtDate, "event timestamp as a date string", params.Time, []string{"evt.date = '2018-03-03'"}, nil, nil}, - EvtDateDay: {EvtDateDay, "day of the month on which the event occurred", params.Time, []string{"evt.date.d = 12"}, nil, nil}, - EvtDateMonth: {EvtDateMonth, "month of the year on which the event occurred", params.Time, []string{"evt.date.m = 11"}, nil, nil}, - EvtDateYear: {EvtDateYear, "year on which the event occurred", params.Uint32, []string{"evt.date.y = 2020"}, nil, nil}, - EvtDateTz: {EvtDateTz, "time zone associated with the event timestamp", params.AnsiString, []string{"evt.date.tz = 'UTC'"}, nil, nil}, - EvtDateWeek: {EvtDateWeek, "week number within the year on which the event occurred", params.Uint8, []string{"evt.date.week = 2"}, nil, nil}, - EvtDateWeekday: {EvtDateWeekday, "week day on which the event occurred", params.AnsiString, []string{"evt.date.weekday = 'Monday'"}, nil, nil}, - EvtNparams: {EvtNparams, "number of parameters", params.Int8, []string{"evt.nparams > 2"}, nil, nil}, - EvtArg: {EvtArg, "event parameter", params.Object, []string{"evt.arg[cmdline] istartswith 'C:\\Windows'"}, nil, &Argument{Optional: false, Pattern: "[a-z0-9_]+", ValidationFunc: func(s string) bool { - for _, c := range s { - switch { - case unicode.IsLower(c): - case unicode.IsNumber(c): - case c == '_': - default: - return false - } - } - return true - }}}, - EvtIsDirectSyscall: {EvtIsDirectSyscall, "indicates if the event is performing a direct syscall", params.Bool, []string{"evt.is_direct_syscall = true"}, nil, nil}, - EvtIsIndirectSyscall: {EvtIsIndirectSyscall, "indicates if the event is performing an indirect syscall", params.Bool, []string{"evt.is_indirect_syscall = true"}, nil, nil}, - - KevtSeq: {KevtSeq, "event sequence number", params.Uint64, []string{"kevt.seq > 666"}, &Deprecation{Since: "3.0.0", Fields: []Field{EvtSeq}}, nil}, - KevtPID: {KevtPID, "process identifier generating the event", params.Uint32, []string{"kevt.pid = 6"}, &Deprecation{Since: "3.0.0", Fields: []Field{EvtPID}}, nil}, - KevtTID: {KevtTID, "thread identifier generating the event", params.Uint32, []string{"kevt.tid = 1024"}, &Deprecation{Since: "3.0.0", Fields: []Field{EvtTID}}, nil}, - KevtCPU: {KevtCPU, "logical processor core where the event was generated", params.Uint8, []string{"kevt.cpu = 2"}, &Deprecation{Since: "3.0.0", Fields: []Field{EvtCPU}}, nil}, - KevtName: {KevtName, "symbolical event name", params.AnsiString, []string{"kevt.name = 'CreateThread'"}, &Deprecation{Since: "3.0.0", Fields: []Field{EvtName}}, nil}, - KevtCategory: {KevtCategory, "event category", params.AnsiString, []string{"kevt.category = 'registry'"}, &Deprecation{Since: "3.0.0", Fields: []Field{EvtCategory}}, nil}, - KevtDesc: {KevtDesc, "event description", params.AnsiString, []string{"kevt.desc contains 'Creates a new process'"}, &Deprecation{Since: "3.0.0", Fields: []Field{EvtDesc}}, nil}, - KevtHost: {KevtHost, "host name on which the event was produced", params.UnicodeString, []string{"kevt.host contains 'kitty'"}, &Deprecation{Since: "3.0.0", Fields: []Field{EvtHost}}, nil}, - KevtTime: {KevtTime, "event timestamp as a time string", params.Time, []string{"kevt.time = '17:05:32'"}, &Deprecation{Since: "3.0.0", Fields: []Field{EvtTime}}, nil}, - KevtTimeHour: {KevtTimeHour, "hour within the day on which the event occurred", params.Time, []string{"kevt.time.h = 23"}, &Deprecation{Since: "3.0.0", Fields: []Field{EvtTimeHour}}, nil}, - KevtTimeMin: {KevtTimeMin, "minute offset within the hour on which the event occurred", params.Time, []string{"kevt.time.m = 54"}, &Deprecation{Since: "3.0.0", Fields: []Field{EvtTimeMin}}, nil}, - KevtTimeSec: {KevtTimeSec, "second offset within the minute on which the event occurred", params.Time, []string{"kevt.time.s = 0"}, &Deprecation{Since: "3.0.0", Fields: []Field{EvtTimeSec}}, nil}, - KevtTimeNs: {KevtTimeNs, "nanoseconds specified by event timestamp", params.Int64, []string{"kevt.time.ns > 1591191629102337000"}, &Deprecation{Since: "3.0.0", Fields: []Field{EvtTimeNs}}, nil}, - KevtDate: {KevtDate, "event timestamp as a date string", params.Time, []string{"kevt.date = '2018-03-03'"}, &Deprecation{Since: "3.0.0", Fields: []Field{EvtDate}}, nil}, - KevtDateDay: {KevtDateDay, "day of the month on which the event occurred", params.Time, []string{"kevt.date.d = 12"}, &Deprecation{Since: "3.0.0", Fields: []Field{EvtDateDay}}, nil}, - KevtDateMonth: {KevtDateMonth, "month of the year on which the event occurred", params.Time, []string{"kevt.date.m = 11"}, &Deprecation{Since: "3.0.0", Fields: []Field{EvtDateMonth}}, nil}, - KevtDateYear: {KevtDateYear, "year on which the event occurred", params.Uint32, []string{"kevt.date.y = 2020"}, &Deprecation{Since: "3.0.0", Fields: []Field{EvtDateYear}}, nil}, - KevtDateTz: {KevtDateTz, "time zone associated with the event timestamp", params.AnsiString, []string{"kevt.date.tz = 'UTC'"}, &Deprecation{Since: "3.0.0", Fields: []Field{EvtDateTz}}, nil}, - KevtDateWeek: {KevtDateWeek, "week number within the year on which the event occurred", params.Uint8, []string{"kevt.date.week = 2"}, &Deprecation{Since: "3.0.0", Fields: []Field{EvtDateWeek}}, nil}, - KevtDateWeekday: {KevtDateWeekday, "week day on which the event occurred", params.AnsiString, []string{"kevt.date.weekday = 'Monday'"}, &Deprecation{Since: "3.0.0", Fields: []Field{EvtDateWeekday}}, nil}, - KevtNparams: {KevtNparams, "number of parameters", params.Int8, []string{"kevt.nparams > 2"}, &Deprecation{Since: "3.0.0", Fields: []Field{EvtNparams}}, nil}, - KevtArg: {KevtArg, "event parameter", params.Object, []string{"kevt.arg[cmdline] istartswith 'C:\\Windows'"}, &Deprecation{Since: "3.0.0", Fields: []Field{EvtArg}}, &Argument{Optional: false, Pattern: "[a-z0-9_]+", ValidationFunc: func(s string) bool { - for _, c := range s { - switch { - case unicode.IsLower(c): - case unicode.IsNumber(c): - case c == '_': - default: - return false - } - } - return true - }}}, - - PsPid: {PsPid, "process identifier", params.PID, []string{"ps.pid = 1024"}, nil, nil}, - PsPpid: {PsPpid, "parent process identifier", params.PID, []string{"ps.ppid = 45"}, nil, nil}, - PsName: {PsName, "process image name including the file extension", params.UnicodeString, []string{"ps.name contains 'firefox'"}, nil, nil}, - PsComm: {PsComm, "process command line", params.UnicodeString, []string{"ps.comm contains 'java'"}, &Deprecation{Since: "1.10.0", Fields: []Field{PsCmdline}}, nil}, - PsCmdline: {PsCmdline, "process command line", params.UnicodeString, []string{"ps.cmdline contains 'java'"}, nil, nil}, - PsExe: {PsExe, "full name of the process' executable", params.UnicodeString, []string{"ps.exe = 'C:\\Windows\\system32\\cmd.exe'"}, nil, nil}, - PsArgs: {PsArgs, "process command line arguments", params.Slice, []string{"ps.args in ('/cdir', '/-C')"}, nil, nil}, - PsCwd: {PsCwd, "process current working directory", params.UnicodeString, []string{"ps.cwd = 'C:\\Users\\Default'"}, nil, nil}, - PsSID: {PsSID, "security identifier under which this process is run", params.UnicodeString, []string{"ps.sid contains 'SYSTEM'"}, nil, nil}, - PsSessionID: {PsSessionID, "unique identifier for the current session", params.Int16, []string{"ps.sessionid = 1"}, nil, nil}, - PsDomain: {PsDomain, "process domain", params.UnicodeString, []string{"ps.domain contains 'SERVICE'"}, nil, nil}, - PsUsername: {PsUsername, "process username", params.UnicodeString, []string{"ps.username contains 'system'"}, nil, nil}, - PsEnvs: {PsEnvs, "process environment variables", params.Slice, []string{"ps.envs in ('SystemRoot:C:\\WINDOWS')", "ps.envs[windir] = 'C:\\WINDOWS'"}, nil, &Argument{Optional: true, ValidationFunc: func(arg string) bool { return true }}}, - PsHandleNames: {PsHandleNames, "allocated process handle names", params.Slice, []string{"ps.handles in ('\\BaseNamedObjects\\__ComCatalogCache__')"}, nil, nil}, - PsHandleTypes: {PsHandleTypes, "allocated process handle types", params.Slice, []string{"ps.handle.types in ('Key', 'Mutant', 'Section')"}, nil, nil}, - PsDTB: {PsDTB, "process directory table base address", params.Address, []string{"ps.dtb = '7ffe0000'"}, nil, nil}, - PsModuleNames: {PsModuleNames, "modules loaded by the process", params.Slice, []string{"ps.modules in ('crypt32.dll', 'xul.dll')"}, nil, nil}, - PsParentName: {PsParentName, "parent process image name including the file extension", params.UnicodeString, []string{"ps.parent.name contains 'cmd.exe'"}, nil, nil}, - PsParentPid: {PsParentPid, "parent process id", params.Uint32, []string{"ps.parent.pid = 4"}, nil, nil}, - PsParentComm: {PsParentComm, "parent process command line", params.UnicodeString, []string{"ps.parent.comm contains 'java'"}, &Deprecation{Since: "1.10.0", Fields: []Field{PsParentCmdline}}, nil}, - PsParentCmdline: {PsParentCmdline, "parent process command line", params.UnicodeString, []string{"ps.parent.cmdline contains 'java'"}, nil, nil}, - PsParentExe: {PsParentExe, "full name of the parent process' executable", params.UnicodeString, []string{"ps.parent.exe = 'C:\\Windows\\system32\\explorer.exe'"}, nil, nil}, - PsParentArgs: {PsParentArgs, "parent process command line arguments", params.Slice, []string{"ps.parent.args in ('/cdir', '/-C')"}, nil, nil}, - PsParentCwd: {PsParentCwd, "parent process current working directory", params.UnicodeString, []string{"ps.parent.cwd = 'C:\\Temp'"}, nil, nil}, - PsParentSID: {PsParentSID, "security identifier under which the parent process is run", params.UnicodeString, []string{"ps.parent.sid contains 'SYSTEM'"}, nil, nil}, - PsParentDomain: {PsParentDomain, "parent process domain", params.UnicodeString, []string{"ps.parent.domain contains 'SERVICE'"}, nil, nil}, - PsParentUsername: {PsParentUsername, "parent process username", params.UnicodeString, []string{"ps.parent.username contains 'system'"}, nil, nil}, - PsParentSessionID: {PsParentSessionID, "unique identifier for the current session of parent process", params.Int16, []string{"ps.parent.sessionid = 1"}, nil, nil}, - PsParentEnvs: {PsParentEnvs, "parent process environment variables", params.Slice, []string{"ps.parent.envs in ('MOZ_CRASHREPORTER_DATA_DIRECTORY')"}, nil, nil}, - PsParentHandles: {PsParentHandles, "allocated parent process handle names", params.Slice, []string{"ps.parent.handles in ('\\BaseNamedObjects\\__ComCatalogCache__')"}, nil, nil}, - PsParentHandleTypes: {PsParentHandleTypes, "allocated parent process handle types", params.Slice, []string{"ps.parent.handle.types in ('File', 'SymbolicLink')"}, nil, nil}, - PsParentDTB: {PsParentDTB, "parent process directory table base address", params.Address, []string{"ps.parent.dtb = '7ffe0000'"}, nil, nil}, - PsAccessMask: {PsAccessMask, "process desired access rights", params.AnsiString, []string{"ps.access.mask = '0x1400'"}, nil, nil}, - PsAccessMaskNames: {PsAccessMaskNames, "process desired access rights as a string list", params.Slice, []string{"ps.access.mask.names in ('SUSPEND_RESUME')"}, nil, nil}, - PsAccessStatus: {PsAccessStatus, "process access status", params.UnicodeString, []string{"ps.access.status = 'access is denied.'"}, nil, nil}, - PsUUID: {PsUUID, "unique process identifier", params.Uint64, []string{"ps.uuid > 6000054355"}, nil, nil}, - PsParentUUID: {PsParentUUID, "unique parent process identifier", params.Uint64, []string{"ps.parent.uuid > 6000054355"}, nil, nil}, - PsIsWOW64Field: {PsIsWOW64Field, "indicates if the process generating the event is a 32-bit process created in 64-bit Windows system", params.Bool, []string{"ps.is_wow64"}, nil, nil}, - PsIsPackagedField: {PsIsPackagedField, "indicates if the process generating the event is packaged with the MSIX technology", params.Bool, []string{"ps.is_packaged"}, nil, nil}, - PsIsProtectedField: {PsIsProtectedField, "indicates if the process generating the event is a protected process", params.Bool, []string{"ps.is_protected"}, nil, nil}, - PsParentIsWOW64Field: {PsParentIsWOW64Field, "indicates if the parent process generating the event is a 32-bit process created in 64-bit Windows system", params.Bool, []string{"ps.parent.is_wow64"}, nil, nil}, - PsParentIsPackagedField: {PsParentIsPackagedField, "indicates if the parent process generating the event is packaged with the MSIX technology", params.Bool, []string{"ps.parent.is_packaged"}, nil, nil}, - PsParentIsProtectedField: {PsParentIsProtectedField, "indicates if the the parent process generating the event is a protected process", params.Bool, []string{"ps.parent.is_protected"}, nil, nil}, - PsAncestor: {PsAncestor, "the process ancestor name", params.UnicodeString, []string{"ps.ancestor[1] = 'svchost.exe'", "ps.ancestor in ('winword.exe')"}, nil, &Argument{Optional: true, Pattern: "[0-9]+", ValidationFunc: isNumber}}, - PsTokenIntegrityLevel: {PsTokenIntegrityLevel, "process token integrity level", params.UnicodeString, []string{"ps.token.integrity_level = 'SYSTEM'"}, nil, nil}, - PsTokenIsElevated: {PsTokenIsElevated, "indicates if the process token is elevated", params.Bool, []string{"ps.token.is_elevated = true"}, nil, nil}, - PsTokenElevationType: {PsTokenElevationType, "process token elevation type", params.AnsiString, []string{"ps.token.elevation_type = 'LIMITED'"}, nil, nil}, - PsParentTokenIntegrityLevel: {PsParentTokenIntegrityLevel, "parent process token integrity level", params.UnicodeString, []string{"ps.parent.token.integrity_level = 'HIGH'"}, nil, nil}, - PsParentTokenIsElevated: {PsParentTokenIsElevated, "indicates if the parent process token is elevated", params.Bool, []string{"ps.parent.token.is_elevated = true"}, nil, nil}, - PsParentTokenElevationType: {PsParentTokenElevationType, "parent process token elevation type", params.AnsiString, []string{"ps.parent.token.elevation_type = 'LIMITED'"}, nil, nil}, - PsSignatureExists: {PsSignatureExists, "indicates if the process executable has a valid signature", params.Bool, []string{"ps.signature.exists"}, nil, nil}, - PsSignatureTrusted: {PsSignatureTrusted, "indicates if the process executable signature certificate chain is trusted", params.Bool, []string{"ps.signature.trusted"}, nil, nil}, - PsSignatureSerial: {PsSignatureSerial, "represents signature serial number", params.UnicodeString, []string{"ps.signature.serial = '330000023241fb59996dcc4dff000000000232'"}, nil, nil}, - PsSignatureSubject: {PsSignatureSubject, "represents signature subject", params.UnicodeString, []string{"ps.signature.subject contains 'Washington, Redmond, Microsoft Corporation'"}, nil, nil}, - PsSignatureIssuer: {PsSignatureIssuer, "represents signature CA", params.UnicodeString, []string{"ps.signature.issuer contains 'Washington, Redmond, Microsoft Corporation'"}, nil, nil}, - PsSignatureAfter: {PsSignatureAfter, "represents certificate expiration date", params.Time, []string{"ps.signature.after contains '2024-02-01 00:05:42 +0000 UTC'"}, nil, nil}, - PsSignatureBefore: {PsSignatureBefore, "represents certificate enrollment date", params.Time, []string{"ps.signature.before contains '2024-02-01 00:05:42 +0000 UTC'"}, nil, nil}, - - PsPeNumSections: {PsPeNumSections, "number of PE sections", params.Uint16, []string{"ps.pe.nsections < 5"}, nil, nil}, - PsPeNumSymbols: {PsPeNumSymbols, "number of entries in the symbol table", params.Uint32, []string{"ps.pe.nsymbols > 230"}, nil, nil}, - PsPeBaseAddress: {PsPeBaseAddress, "executable base address", params.Address, []string{"ps.pe.address.base = '140000000'"}, nil, nil}, - PsPeEntrypoint: {PsPeEntrypoint, "address of the entrypoint function", params.Address, []string{"ps.pe.address.entrypoint = '20110'"}, nil, nil}, - PsPeSymbols: {PsPeSymbols, "imported symbols", params.Slice, []string{"ps.pe.symbols in ('GetTextFaceW', 'GetProcessHeap')"}, nil, nil}, - PsPeImports: {PsPeImports, "imported dynamic linked libraries", params.Slice, []string{"ps.pe.imports in ('msvcrt.dll', 'GDI32.dll'"}, nil, nil}, - PsPeResources: {PsPeResources, "version resources", params.Map, []string{"ps.pe.resources[FileDescription] = 'Notepad'"}, nil, &Argument{Optional: true, Pattern: "[a-zA-Z0-9_]+", ValidationFunc: func(s string) bool { - for _, c := range s { - switch { - case unicode.IsLower(c): - case unicode.IsUpper(c): - case unicode.IsNumber(c): - case c == '_': - default: - return false - } - } - return true - }}}, - PsPeCompany: {PsPeCompany, "internal company name of the file provided at compile-time", params.UnicodeString, []string{"ps.pe.company = 'Microsoft Corporation'"}, nil, nil}, - PsPeCopyright: {PsPeCopyright, "copyright notice for the file emitted at compile-time", params.UnicodeString, []string{"ps.pe.copyright = '© Microsoft Corporation'"}, nil, nil}, - PsPeDescription: {PsPeDescription, "internal description of the file provided at compile-time", params.UnicodeString, []string{"ps.pe.description = 'Notepad'"}, nil, nil}, - PsPeFileName: {PsPeFileName, "original file name supplied at compile-time", params.UnicodeString, []string{"ps.pe.file.name = 'NOTEPAD.EXE'"}, nil, nil}, - PsPeFileVersion: {PsPeFileVersion, "file version supplied at compile-time", params.UnicodeString, []string{"ps.pe.file.version = '10.0.18362.693 (WinBuild.160101.0800)'"}, nil, nil}, - PsPeProduct: {PsPeProduct, "internal product name of the file provided at compile-time", params.UnicodeString, []string{"ps.pe.product = 'Microsoft® Windows® Operating System'"}, nil, nil}, - PsPeProductVersion: {PsPeProductVersion, "internal product version of the file provided at compile-time", params.UnicodeString, []string{"ps.pe.product.version = '10.0.18362.693'"}, nil, nil}, - PsPeImphash: {PsPeImphash, "import hash", params.AnsiString, []string{"pe.impash = '5d3861c5c547f8a34e471ba273a732b2'"}, nil, nil}, - PsPeIsDotnet: {PsPeIsDotnet, "indicates if PE contains CLR data", params.Bool, []string{"ps.pe.is_dotnet"}, nil, nil}, - PsPeAnomalies: {PsPeAnomalies, "contains PE anomalies detected during parsing", params.Slice, []string{"ps.pe.anomalies in ('number of sections is 0')"}, nil, nil}, - PsPeIsModified: {PsPeIsModified, "indicates if disk and in-memory PE headers differ", params.Bool, []string{"ps.pe.is_modified"}, nil, nil}, - - ThreadBasePrio: {ThreadBasePrio, "scheduler priority of the thread", params.Int8, []string{"thread.prio = 5"}, nil, nil}, - ThreadIOPrio: {ThreadIOPrio, "I/O priority hint for scheduling I/O operations", params.Int8, []string{"thread.io.prio = 4"}, nil, nil}, - ThreadPagePrio: {ThreadPagePrio, "memory page priority hint for memory pages accessed by the thread", params.Int8, []string{"thread.page.prio = 12"}, nil, nil}, - ThreadKstackBase: {ThreadKstackBase, "base address of the thread's kernel space stack", params.Address, []string{"thread.kstack.base = 'a65d800000'"}, nil, nil}, - ThreadKstackLimit: {ThreadKstackLimit, "limit of the thread's kernel space stack", params.Address, []string{"thread.kstack.limit = 'a85d800000'"}, nil, nil}, - ThreadUstackBase: {ThreadUstackBase, "base address of the thread's user space stack", params.Address, []string{"thread.ustack.base = '7ffe0000'"}, nil, nil}, - ThreadUstackLimit: {ThreadUstackLimit, "limit of the thread's user space stack", params.Address, []string{"thread.ustack.limit = '8ffe0000'"}, nil, nil}, - ThreadEntrypoint: {ThreadEntrypoint, "starting address of the function to be executed by the thread", params.Address, []string{"thread.entrypoint = '7efe0000'"}, &Deprecation{Since: "2.3.0", Fields: []Field{ThreadStartAddress}}, nil}, - ThreadStartAddress: {ThreadStartAddress, "thread start address", params.Address, []string{"thread.start_address = '7efe0000'"}, nil, nil}, - ThreadStartAddressSymbol: {ThreadStartAddressSymbol, "thread start address symbol", params.UnicodeString, []string{"thread.start_address.symbol = 'LoadModule'"}, nil, nil}, - ThreadStartAddressModule: {ThreadStartAddressModule, "thread start address module", params.UnicodeString, []string{"thread.start_address.module endswith 'kernel32.dll'"}, nil, nil}, - ThreadPID: {ThreadPID, "the process identifier where the thread is created", params.Uint32, []string{"evt.pid != thread.pid"}, nil, nil}, - ThreadTEB: {ThreadTEB, "the base address of the thread environment block", params.Address, []string{"thread.teb_address = '8f30893000'"}, nil, nil}, - ThreadAccessMask: {ThreadAccessMask, "thread desired access rights", params.AnsiString, []string{"thread.access.mask = '0x1fffff'"}, nil, nil}, - ThreadAccessMaskNames: {ThreadAccessMaskNames, "thread desired access rights as a string list", params.Slice, []string{"thread.access.mask.names in ('IMPERSONATE')"}, nil, nil}, - ThreadAccessStatus: {ThreadAccessStatus, "thread access status", params.UnicodeString, []string{"thread.access.status = 'success'"}, nil, nil}, - ThreadCallstackSummary: {ThreadCallstackSummary, "callstack summary", params.UnicodeString, []string{"thread.callstack.summary contains 'ntdll.dll|KERNELBASE.dll'"}, nil, nil}, - ThreadCallstackKernelSummary: {ThreadCallstackKernelSummary, "kernel thread callstack summary", params.UnicodeString, []string{"thread.callstack.kernel_summary contains 'fileinfo.sys|ntoskrnl.exe|FLTMGR.SYS|ntoskrnl.exe'"}, nil, nil}, - ThreadCallstackDetail: {ThreadCallstackDetail, "detailed information of each stack frame", params.UnicodeString, []string{"thread.callstack.detail contains 'KERNELBASE.dll!CreateProcessW'"}, nil, nil}, - ThreadCallstackModules: {ThreadCallstackModules, "list of modules comprising the callstack", params.Slice, []string{"thread.callstack.modules in ('C:\\WINDOWS\\System32\\KERNELBASE.dll')", "base(thread.callstack.modules[7]) = 'ntdll.dll'"}, nil, &Argument{Optional: true, Pattern: "[0-9]+", ValidationFunc: isNumber}}, - ThreadCallstackSymbols: {ThreadCallstackSymbols, "list of symbols comprising the callstack", params.Slice, []string{"thread.callstack.symbols in ('ntdll.dll!NtCreateProcess')", "thread.callstack.symbols[3] = 'ntdll!NtCreateProcess'"}, nil, &Argument{Optional: true, Pattern: "[0-9]+", ValidationFunc: isNumber}}, - ThreadCallstackAllocationSizes: {ThreadCallstackAllocationSizes, "allocation sizes of private pages", params.Slice, []string{"thread.callstack.allocation_sizes > 10000"}, nil, nil}, - ThreadCallstackProtections: {ThreadCallstackProtections, "page protections masks of each frame", params.Slice, []string{"thread.callstack.protections in ('RWX', 'WX')"}, nil, nil}, - ThreadCallstackCallsiteLeadingAssembly: {ThreadCallstackCallsiteLeadingAssembly, "callsite leading assembly instructions", params.Slice, []string{"thread.callstack.callsite_leading_assembly in ('mov r10,rcx', 'syscall')"}, nil, nil}, - ThreadCallstackCallsiteTrailingAssembly: {ThreadCallstackCallsiteTrailingAssembly, "callsite trailing assembly instructions", params.Slice, []string{"thread.callstack.callsite_trailing_assembly in ('add esp, 0xab')"}, nil, nil}, - ThreadCallstackIsUnbacked: {ThreadCallstackIsUnbacked, "indicates if the callstack contains unbacked regions", params.Bool, []string{"thread.callstack.is_unbacked"}, nil, nil}, - ThreadCallstackAddresses: {ThreadCallstackAddresses, "list of all stack return addresses", params.Slice, []string{"thread.callstack.addresses in ('7ffb5c1d0396')"}, nil, nil}, - ThreadCallstackFinalUserModuleName: {ThreadCallstackFinalUserModuleName, "final user space stack frame module name", params.UnicodeString, []string{"thread.callstack.final_user_module.name != 'ntdll.dll'"}, nil, nil}, - ThreadCallstackFinalUserModulePath: {ThreadCallstackFinalUserModulePath, "final user space stack frame module path", params.UnicodeString, []string{"thread.callstack.final_user_module.path imatches '?:\\Windows\\System32\\ntdll.dll'"}, nil, nil}, - ThreadCallstackFinalUserSymbolName: {ThreadCallstackFinalUserSymbolName, "final user space stack symbol name", params.UnicodeString, []string{"thread.callstack.final_user_symbol.name imatches 'CreateProcess*'"}, nil, nil}, - ThreadCallstackFinalKernelModuleName: {ThreadCallstackFinalKernelModuleName, "final kernel space stack frame module name", params.UnicodeString, []string{"thread.callstack.final_kernel_module.name = 'FLTMGR.SYS'"}, nil, nil}, - ThreadCallstackFinalKernelModulePath: {ThreadCallstackFinalKernelModulePath, "final kernel space stack frame module path", params.UnicodeString, []string{"thread.callstack.final_kernel_module.path imatches '?:\\WINDOWS\\System32\\drivers\\FLTMGR.SYS'"}, nil, nil}, - ThreadCallstackFinalKernelSymbolName: {ThreadCallstackFinalKernelSymbolName, "final kernel space stack symbol name", params.UnicodeString, []string{"thread.callstack.final_kernel_symbol.name = 'FltGetStreamContext'"}, nil, nil}, - ThreadCallstackFinalUserModuleSignatureExists: {ThreadCallstackFinalUserModuleSignatureExists, "signature status of the final user space stack frame module", params.Bool, []string{"thread.callstack.final_user_module.signature.exists = true"}, nil, nil}, - ThreadCallstackFinalUserModuleSignatureTrusted: {ThreadCallstackFinalUserModuleSignatureTrusted, "signature trust status of the final user space stack frame module", params.Bool, []string{"thread.callstack.final_user_module.signature.trusted = true"}, nil, nil}, - ThreadCallstackFinalUserModuleSignatureIssuer: {ThreadCallstackFinalUserModuleSignatureIssuer, "final user space stack frame module signature certificate issuer", params.UnicodeString, []string{"thread.callstack.final_user_module.signature.issuer imatches '*Microsoft Corporation*'"}, nil, nil}, - ThreadCallstackFinalUserModuleSignatureSubject: {ThreadCallstackFinalUserModuleSignatureSubject, "final user space stack frame module signature certificate subject", params.UnicodeString, []string{"thread.callstack.final_user_module.signature.subject imatches '*Microsoft Windows*'"}, nil, nil}, - - ImagePath: {ImagePath, "full image path", params.UnicodeString, []string{"image.path = 'C:\\Windows\\System32\\advapi32.dll'"}, &Deprecation{Since: "3.0.0", Fields: []Field{ModulePath}}, nil}, - ImageName: {ImageName, "image name", params.UnicodeString, []string{"image.name = 'advapi32.dll'"}, &Deprecation{Since: "3.0.0", Fields: []Field{ModuleName}}, nil}, - ImageBase: {ImageBase, "the base address of process in which the image is loaded", params.Address, []string{"image.base.address = 'a65d800000'"}, &Deprecation{Since: "3.0.0", Fields: []Field{ModuleBase}}, nil}, - ImageChecksum: {ImageChecksum, "image checksum", params.Uint32, []string{"image.checksum = 746424"}, &Deprecation{Since: "3.0.0", Fields: []Field{ModuleChecksum}}, nil}, - ImageSize: {ImageSize, "image size", params.Uint32, []string{"image.size > 1024"}, &Deprecation{Since: "3.0.0", Fields: []Field{ModuleSize}}, nil}, - ImageDefaultAddress: {ImageDefaultAddress, "default image address", params.Address, []string{"image.default.address = '7efe0000'"}, &Deprecation{Since: "3.0.0", Fields: []Field{ModuleDefaultAddress}}, nil}, - ImagePID: {ImagePID, "target process identifier", params.Uint32, []string{"image.pid = 80"}, &Deprecation{Since: "3.0.0", Fields: []Field{ModulePID}}, nil}, - ImageSignatureType: {ImageSignatureType, "image signature type", params.AnsiString, []string{"image.signature.type != 'NONE'"}, &Deprecation{Since: "3.0.0", Fields: []Field{ModuleSignatureType}}, nil}, - ImageSignatureLevel: {ImageSignatureLevel, "image signature level", params.AnsiString, []string{"image.signature.level = 'AUTHENTICODE'"}, &Deprecation{Since: "3.0.0", Fields: []Field{ModuleSignatureLevel}}, nil}, - ImageCertSerial: {ImageCertSerial, "image certificate serial number", params.UnicodeString, []string{"image.cert.serial = '330000023241fb59996dcc4dff000000000232'"}, &Deprecation{Since: "3.0.0", Fields: []Field{ModuleSignatureSerial}}, nil}, - ImageCertSubject: {ImageCertSubject, "image certificate subject", params.UnicodeString, []string{"image.cert.subject contains 'Washington, Redmond, Microsoft Corporation'"}, &Deprecation{Since: "3.0.0", Fields: []Field{ModuleSignatureSubject}}, nil}, - ImageCertIssuer: {ImageCertIssuer, "image certificate CA", params.UnicodeString, []string{"image.cert.issuer contains 'Washington, Redmond, Microsoft Corporation'"}, &Deprecation{Since: "3.0.0", Fields: []Field{ModuleSignatureIssuer}}, nil}, - ImageCertAfter: {ImageCertAfter, "image certificate expiration date", params.Time, []string{"image.cert.after contains '2024-02-01 00:05:42 +0000 UTC'"}, &Deprecation{Since: "3.0.0", Fields: []Field{ModuleSignatureAfter}}, nil}, - ImageCertBefore: {ImageCertBefore, "image certificate enrollment date", params.Time, []string{"image.cert.before contains '2024-02-01 00:05:42 +0000 UTC'"}, &Deprecation{Since: "3.0.0", Fields: []Field{ModuleSignatureBefore}}, nil}, - ImageIsDLL: {ImageIsDLL, "indicates if the loaded image is a DLL", params.Bool, []string{"image.is_dll'"}, &Deprecation{Since: "3.0.0", Fields: []Field{ModuleIsDLL}}, nil}, - ImageIsDriver: {ImageIsDriver, "indicates if the loaded image is a driver", params.Bool, []string{"image.is_driver'"}, &Deprecation{Since: "3.0.0", Fields: []Field{ModuleIsDriver}}, nil}, - ImageIsExecutable: {ImageIsExecutable, "indicates if the loaded image is an executable", params.Bool, []string{"image.is_exec'"}, &Deprecation{Since: "3.0.0", Fields: []Field{ModuleIsExecutable}}, nil}, - ImageIsDotnet: {ImageIsDotnet, "indicates if the loaded image is a .NET assembly", params.Bool, []string{"image.is_dotnet'"}, &Deprecation{Since: "3.0.0", Fields: []Field{ModuleIsDotnet}}, nil}, - ModulePath: {ModulePath, "full module path", params.UnicodeString, []string{"module.path = 'C:\\Windows\\System32\\advapi32.dll'"}, nil, nil}, - ModulePathStem: {ModulePathStem, "module path stem", params.UnicodeString, []string{"module.path.stem = 'C:\\Windows\\System32\\advapi32'"}, nil, nil}, - ModuleName: {ModuleName, "module name", params.UnicodeString, []string{"module.name = 'advapi32.dll'"}, nil, nil}, - ModuleBase: {ModuleBase, "the base address of process in which the module is loaded", params.Address, []string{"module.base.address = 'a65d800000'"}, nil, nil}, - ModuleChecksum: {ModuleChecksum, "module checksum", params.Uint32, []string{"module.checksum = 746424"}, nil, nil}, - ModuleSize: {ModuleSize, "module size", params.Uint32, []string{"module.size > 1024"}, nil, nil}, - ModuleDefaultAddress: {ModuleDefaultAddress, "default module address", params.Address, []string{"module.default_address = '7efe0000'"}, nil, nil}, - ModulePID: {ModulePID, "target process identifier", params.Uint32, []string{"module.pid = 80"}, nil, nil}, - ModuleSignatureType: {ModuleSignatureType, "module signature type", params.AnsiString, []string{"module.signature.type != 'NONE'"}, nil, nil}, - ModuleSignatureLevel: {ModuleSignatureLevel, "module signature level", params.AnsiString, []string{"module.signature.level = 'AUTHENTICODE'"}, nil, nil}, - ModuleSignatureExists: {ModuleSignatureExists, "indicates if the module is signed", params.Bool, []string{"module.signature.exists = true"}, nil, nil}, - ModuleSignatureTrusted: {ModuleSignatureTrusted, "indicates if the module signature is trusted", params.Bool, []string{"module.signature.trusted = false"}, nil, nil}, - ModuleSignatureSerial: {ModuleSignatureSerial, "module certificate serial number", params.UnicodeString, []string{"module.signature.serial = '330000023241fb59996dcc4dff000000000232'"}, nil, nil}, - ModuleSignatureSubject: {ModuleSignatureSubject, "module certificate subject", params.UnicodeString, []string{"module.signature.subject contains 'Washington, Redmond, Microsoft Corporation'"}, nil, nil}, - ModuleSignatureIssuer: {ModuleSignatureIssuer, "module certificate CA", params.UnicodeString, []string{"module.signature.issuer contains 'Washington, Redmond, Microsoft Corporation'"}, nil, nil}, - ModuleSignatureAfter: {ModuleSignatureAfter, "module certificate expiration date", params.Time, []string{"module.signature.after contains '2024-02-01 00:05:42 +0000 UTC'"}, nil, nil}, - ModuleSignatureBefore: {ModuleSignatureBefore, "module certificate enrollment date", params.Time, []string{"module.signature.before contains '2024-02-01 00:05:42 +0000 UTC'"}, nil, nil}, - ModuleIsDLL: {ModuleIsDLL, "indicates if the loaded module is a DLL", params.Bool, []string{"module.is_dll'"}, nil, nil}, - ModuleIsDriver: {ModuleIsDriver, "indicates if the loaded module is a driver", params.Bool, []string{"module.is_driver'"}, nil, nil}, - ModuleIsExecutable: {ModuleIsExecutable, "indicates if the loaded module is an executable", params.Bool, []string{"module.is_exec'"}, nil, nil}, - ModuleIsDotnet: {ModuleIsDotnet, "indicates if the loaded module is a .NET assembly", params.Bool, []string{"module.pe.is_dotnet'"}, nil, nil}, - DllPath: {DllPath, "full dll path", params.UnicodeString, []string{"dll.path = 'C:\\Windows\\System32\\advapi32.dll'"}, nil, nil}, - DllPathStem: {DllPathStem, "dll path stem", params.UnicodeString, []string{"dll.path.stem = 'C:\\Windows\\System32\\advapi32'"}, nil, nil}, - DllName: {DllName, "module name", params.UnicodeString, []string{"dll.name = 'advapi32.dll'"}, nil, nil}, - DllBase: {DllBase, "the base address of process in which the DLL is loaded", params.Address, []string{"dll.base = 'a65d800000'"}, nil, nil}, - DllSize: {DllSize, "dll virtual mapped size", params.Uint32, []string{"dll.size > 1024"}, nil, nil}, - DllPID: {DllPID, "target process identifier", params.Uint32, []string{"dll.pid = 80"}, nil, nil}, - DllSignatureType: {DllSignatureType, "dll signature type", params.AnsiString, []string{"dll.signature.type != 'NONE'"}, nil, nil}, - DllSignatureLevel: {DllSignatureLevel, "dll signature level", params.AnsiString, []string{"dll.signature.level = 'AUTHENTICODE'"}, nil, nil}, - DllSignatureExists: {DllSignatureExists, "indicates if the dll is signed", params.Bool, []string{"dll.signature.exists = true"}, nil, nil}, - DllSignatureTrusted: {DllSignatureTrusted, "indicates if the dll signature is trusted", params.Bool, []string{"dll.signature.trusted = false"}, nil, nil}, - DllSignatureSerial: {DllSignatureSerial, "dll certificate serial number", params.UnicodeString, []string{"dll.signature.serial = '330000023241fb59996dcc4dff000000000232'"}, nil, nil}, - DllSignatureSubject: {DllSignatureSubject, "dll certificate subject", params.UnicodeString, []string{"dll.signature.subject contains 'Washington, Redmond, Microsoft Corporation'"}, nil, nil}, - DllSignatureIssuer: {DllSignatureIssuer, "dll certificate CA", params.UnicodeString, []string{"dll.signature.issuer contains 'Washington, Redmond, Microsoft Corporation'"}, nil, nil}, - DllSignatureAfter: {DllSignatureAfter, "moddllule certificate expiration date", params.Time, []string{"dll.signature.after contains '2024-02-01 00:05:42 +0000 UTC'"}, nil, nil}, - DllSignatureBefore: {DllSignatureBefore, "dll certificate enrollment date", params.Time, []string{"dll.signature.before contains '2024-02-01 00:05:42 +0000 UTC'"}, nil, nil}, - DllIsDotnet: {DllIsDotnet, "indicates if the loaded dll is a .NET assembly", params.Bool, []string{"dll.pe.is_dotnet'"}, nil, nil}, - - FileObject: {FileObject, "file object address", params.Uint64, []string{"file.object = 18446738026482168384"}, nil, nil}, - FilePath: {FilePath, "full file path", params.UnicodeString, []string{"file.path = 'C:\\Windows\\System32'"}, nil, nil}, - FilePathStem: {FilePathStem, "full file path without extension", params.UnicodeString, []string{"file.path.stem = 'C:\\Windows\\System32\\cmd'"}, nil, nil}, - FileName: {FileName, "full file name", params.UnicodeString, []string{"file.name contains 'mimikatz'"}, nil, nil}, - FileOperation: {FileOperation, "file operation", params.AnsiString, []string{"file.operation = 'open'"}, nil, nil}, - FileShareMask: {FileShareMask, "file share mask", params.AnsiString, []string{"file.share.mask = 'READ'"}, &Deprecation{Since: "3.1.0", Fields: []Field{FileShareMode}}, nil}, - FileShareMode: {FileShareMask, "file share mode", params.AnsiString, []string{"file.share_mode = 'DENY'"}, nil, nil}, - FileIOSize: {FileIOSize, "file I/O size", params.Uint32, []string{"file.io.size > 512"}, nil, nil}, - FileOffset: {FileOffset, "file offset", params.Uint64, []string{"file.offset = 1024"}, nil, nil}, - FileType: {FileType, "file type", params.AnsiString, []string{"file.type = 'directory'"}, nil, nil}, - FileExtension: {FileExtension, "file extension", params.AnsiString, []string{"file.extension = '.dll'"}, nil, nil}, - FileAttributes: {FileAttributes, "file attributes", params.Slice, []string{"file.attributes in ('archive', 'hidden')"}, nil, nil}, - FileStatus: {FileStatus, "file operation status message", params.UnicodeString, []string{"file.status != 'success'"}, nil, nil}, - FileViewBase: {FileViewBase, "view base address", params.Address, []string{"file.view.base = '25d42170000'"}, nil, nil}, - FileViewSize: {FileViewSize, "size of the mapped view", params.Uint64, []string{"file.view.size > 1024"}, nil, nil}, - FileViewType: {FileViewType, "type of the mapped view section", params.Enum, []string{"file.view.type = 'IMAGE'"}, nil, nil}, - FileViewProtection: {FileViewProtection, "protection rights of the section view", params.AnsiString, []string{"file.view.protection = 'READONLY'"}, nil, nil}, - FileIsDLL: {FileIsDLL, "indicates if the created file is a DLL", params.Bool, []string{"file.is_dll'"}, nil, nil}, - FileIsDriver: {FileIsDriver, "indicates if the created file is a driver", params.Bool, []string{"file.is_driver'"}, nil, nil}, - FileIsExecutable: {FileIsExecutable, "indicates if the created file is an executable", params.Bool, []string{"file.is_exec'"}, nil, nil}, - FilePID: {FilePID, "denotes the process id performing file operation", params.PID, []string{"file.pid = 4"}, nil, nil}, - FileKey: {FileKey, "uniquely identifies the file object", params.Uint64, []string{"file.key = 12446738026482168384"}, nil, nil}, - FileInfoClass: {FileInfoClass, "identifies the file information class", params.Enum, []string{"file.info_class = 'Allocation'"}, nil, nil}, - FileInfoAllocationSize: {FileInfoAllocationSize, "file allocation size", params.Uint64, []string{"file.info.allocation_size > 645400"}, nil, nil}, - FileInfoEOFSize: {FileInfoEOFSize, "file EOF size", params.Uint64, []string{"file.info.eof_size > 1000"}, nil, nil}, - FileInfoIsDispositionDeleteFile: {FileInfoIsDispositionDeleteFile, "indicates if the file is deleted when its handle is closed", params.Bool, []string{"file.info.is_disposition_file_delete = true"}, nil, nil}, - - RegistryPath: {RegistryPath, "fully qualified registry path", params.UnicodeString, []string{"registry.path = 'HKEY_LOCAL_MACHINE\\SYSTEM'"}, nil, nil}, - RegistryKeyName: {RegistryKeyName, "registry key name", params.UnicodeString, []string{"registry.key.name = 'CurrentControlSet'"}, nil, nil}, - RegistryKCB: {RegistryKCB, "registry KCB address", params.Address, []string{"registry.kcb = 'FFFFB905D60C2268'"}, nil, nil}, - RegistryValue: {RegistryValue, "registry value name", params.UnicodeString, []string{"registry.value = 'Epoch'"}, nil, nil}, - RegistryValueType: {RegistryValueType, "type of registry value", params.UnicodeString, []string{"registry.value.type = 'REG_SZ'"}, nil, nil}, - RegistryData: {RegistryData, "registry value captured data", params.Object, []string{"registry.data = '%SystemRoot%'"}, nil, nil}, - RegistryStatus: {RegistryStatus, "status of registry operation", params.UnicodeString, []string{"registry.status != 'success'"}, nil, nil}, - - NetDIP: {NetDIP, "destination IP address", params.IP, []string{"net.dip = 172.17.0.3"}, nil, nil}, - NetSIP: {NetSIP, "source IP address", params.IP, []string{"net.sip = 127.0.0.1"}, nil, nil}, - NetDport: {NetDport, "destination port", params.Uint16, []string{"net.dport in (80, 443, 8080)"}, nil, nil}, - NetSport: {NetSport, "source port", params.Uint16, []string{"net.sport != 3306"}, nil, nil}, - NetDportName: {NetDportName, "destination port name", params.AnsiString, []string{"net.dport.name = 'dns'"}, nil, nil}, - NetSportName: {NetSportName, "source port name", params.AnsiString, []string{"net.sport.name = 'http'"}, nil, nil}, - NetL4Proto: {NetL4Proto, "layer 4 protocol name", params.AnsiString, []string{"net.l4.proto = 'TCP"}, nil, nil}, - NetPacketSize: {NetPacketSize, "packet size", params.Uint32, []string{"net.size > 512"}, nil, nil}, - NetSIPNames: {NetSIPNames, "source IP names", params.Slice, []string{"net.sip.names in ('github.com.')"}, nil, nil}, - NetDIPNames: {NetDIPNames, "destination IP names", params.Slice, []string{"net.dip.names in ('github.com.')"}, nil, nil}, - - HandleID: {HandleID, "handle identifier", params.Uint16, []string{"handle.id = 24"}, nil, nil}, - HandleObject: {HandleObject, "handle object address", params.Address, []string{"handle.object = 'FFFFB905DBF61988'"}, nil, nil}, - HandleName: {HandleName, "handle name", params.UnicodeString, []string{"handle.name = '\\Device\\NamedPipe\\chrome.12644.28.105826381'"}, nil, nil}, - HandleType: {HandleType, "handle type", params.AnsiString, []string{"handle.type = 'Mutant'"}, nil, nil}, - - PeNumSections: {PeNumSections, "number of sections", params.Uint16, []string{"pe.nsections < 5"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsPeNumSections}}, nil}, - PeNumSymbols: {PeNumSymbols, "number of entries in the symbol table", params.Uint32, []string{"pe.nsymbols > 230"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsPeNumSymbols}}, nil}, - PeBaseAddress: {PeBaseAddress, "image base address", params.Address, []string{"pe.address.base = '140000000'"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsPeBaseAddress}}, nil}, - PeEntrypoint: {PeEntrypoint, "address of the entrypoint function", params.Address, []string{"pe.address.entrypoint = '20110'"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsPeEntrypoint}}, nil}, - PeSymbols: {PeSymbols, "imported symbols", params.Slice, []string{"pe.symbols in ('GetTextFaceW', 'GetProcessHeap')"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsPeSymbols}}, nil}, - PeImports: {PeImports, "imported dynamic linked libraries", params.Slice, []string{"pe.imports in ('msvcrt.dll', 'GDI32.dll'"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsPeImports}}, nil}, - - PeResources: {PeResources, "version resources", params.Map, []string{"pe.resources[FileDescription] = 'Notepad'"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsPeResources}}, &Argument{Optional: true, Pattern: "[a-zA-Z0-9_]+", ValidationFunc: func(s string) bool { - for _, c := range s { - switch { - case unicode.IsLower(c): - case unicode.IsUpper(c): - case unicode.IsNumber(c): - case c == '_': - default: - return false - } - } - return true - }}}, - - PeCompany: {PeCompany, "internal company name of the file provided at compile-time", params.UnicodeString, []string{"pe.company = 'Microsoft Corporation'"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsPeCompany}}, nil}, - PeCopyright: {PeCopyright, "copyright notice for the file emitted at compile-time", params.UnicodeString, []string{"pe.copyright = '© Microsoft Corporation'"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsPeCopyright}}, nil}, - PeDescription: {PeDescription, "internal description of the file provided at compile-time", params.UnicodeString, []string{"pe.description = 'Notepad'"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsPeDescription}}, nil}, - PeFileName: {PeFileName, "original file name supplied at compile-time", params.UnicodeString, []string{"pe.file.name = 'NOTEPAD.EXE'"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsPeFileName}}, nil}, - PeFileVersion: {PeFileVersion, "file version supplied at compile-time", params.UnicodeString, []string{"pe.file.version = '10.0.18362.693 (WinBuild.160101.0800)'"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsPeFileVersion}}, nil}, - PeProduct: {PeProduct, "internal product name of the file provided at compile-time", params.UnicodeString, []string{"pe.product = 'Microsoft® Windows® Operating System'"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsPeProduct}}, nil}, - PeProductVersion: {PeProductVersion, "internal product version of the file provided at compile-time", params.UnicodeString, []string{"pe.product.version = '10.0.18362.693'"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsPeProductVersion}}, nil}, - PeIsDLL: {PeIsDLL, "indicates if the loaded image or created file is a DLL", params.Bool, []string{"pe.is_dll'"}, &Deprecation{Since: "2.0.0", Fields: []Field{FileIsDLL, ImageIsDLL}}, nil}, - PeIsDriver: {PeIsDriver, "indicates if the loaded image or created file is a driver", params.Bool, []string{"pe.is_driver'"}, &Deprecation{Since: "2.0.0", Fields: []Field{FileIsDriver, ImageIsDriver}}, nil}, - PeIsExecutable: {PeIsExecutable, "indicates if the loaded image or created file is an executable", params.Bool, []string{"pe.is_exec'"}, &Deprecation{Since: "2.0.0", Fields: []Field{FileIsExecutable, ImageIsExecutable}}, nil}, - PeImphash: {PeImphash, "import hash", params.AnsiString, []string{"pe.impash = '5d3861c5c547f8a34e471ba273a732b2'"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsPeImphash}}, nil}, - PeIsDotnet: {PeIsDotnet, "indicates if PE contains CLR data", params.Bool, []string{"pe.is_dotnet"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsPeIsDotnet}}, nil}, - PeAnomalies: {PeAnomalies, "contains PE anomalies detected during parsing", params.Slice, []string{"pe.anomalies in ('number of sections is 0')"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsPeAnomalies}}, nil}, - PeIsSigned: {PeIsSigned, "indicates if the PE has embedded or catalog signature", params.Bool, []string{"pe.is_signed"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsSignatureExists}}, nil}, - PeIsTrusted: {PeIsTrusted, "indicates if the PE certificate chain is trusted", params.Bool, []string{"pe.is_trusted"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsSignatureTrusted}}, nil}, - PeCertSerial: {PeCertSerial, "PE certificate serial number", params.UnicodeString, []string{"pe.cert.serial = '330000023241fb59996dcc4dff000000000232'"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsSignatureSerial}}, nil}, - PeCertSubject: {PeCertSubject, "PE certificate subject", params.UnicodeString, []string{"pe.cert.subject contains 'Washington, Redmond, Microsoft Corporation'"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsSignatureSubject}}, nil}, - PeCertIssuer: {PeCertIssuer, "PE certificate CA", params.UnicodeString, []string{"pe.cert.issuer contains 'Washington, Redmond, Microsoft Corporation'"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsSignatureIssuer}}, nil}, - PeCertAfter: {PeCertAfter, "PE certificate expiration date", params.Time, []string{"pe.cert.after contains '2024-02-01 00:05:42 +0000 UTC'"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsSignatureAfter}}, nil}, - PeCertBefore: {PeCertBefore, "PE certificate enrollment date", params.Time, []string{"pe.cert.before contains '2024-02-01 00:05:42 +0000 UTC'"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsSignatureBefore}}, nil}, - PeIsModified: {PeIsModified, "indicates if disk and in-memory PE headers differ", params.Bool, []string{"pe.is_modified"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsPeIsModified}}, nil}, - - MemBaseAddress: {MemBaseAddress, "region base address", params.Address, []string{"mem.address = '211d13f2000'"}, nil, nil}, - MemRegionSize: {MemRegionSize, "region size", params.Uint64, []string{"mem.size > 438272"}, nil, nil}, - MemAllocType: {MemAllocType, "region allocation or release type", params.Flags, []string{"mem.alloc = 'COMMIT'"}, nil, nil}, - MemPageType: {MemPageType, "page type of the allocated region", params.Enum, []string{"mem.type = 'PRIVATE'"}, nil, nil}, - MemProtection: {MemProtection, "allocated region protection type", params.Enum, []string{"mem.protection = 'READWRITE'"}, nil, nil}, - MemProtectionMask: {MemProtectionMask, "allocated region protection in mask notation", params.Enum, []string{"mem.protection.mask = 'RWX'"}, nil, nil}, - - DNSName: {DNSName, "dns query name", params.UnicodeString, []string{"dns.name = 'example.org'"}, nil, nil}, - DNSRR: {DNSRR, "dns resource record type", params.AnsiString, []string{"dns.rr = 'AA'"}, nil, nil}, - DNSOptions: {DNSOptions, "dns query options", params.Flags64, []string{"dns.options in ('ADDRCONFIG', 'DUAL_ADDR')"}, nil, nil}, - DNSRcode: {DNSRR, "dns response status", params.AnsiString, []string{"dns.rcode = 'NXDOMAIN'"}, nil, nil}, - DNSAnswers: {DNSAnswers, "dns response answers", params.Slice, []string{"dns.answers in ('o.lencr.edgesuite.net', 'a1887.dscq.akamai.net')"}, nil, nil}, - - ThreadpoolPoolID: {ThreadpoolPoolID, "thread pool identifier", params.Address, []string{"threadpool.id = '20f5fc02440'"}, nil, nil}, - ThreadpoolTaskID: {ThreadpoolTaskID, "thread pool task identifier", params.Address, []string{"threadpool.task.id = '20f7ecd21f8'"}, nil, nil}, - ThreadpoolCallbackAddress: {ThreadpoolCallbackAddress, "thread pool callback address", params.Address, []string{"threadpool.callback.address = '7ff868739ed0'"}, nil, nil}, - ThreadpoolCallbackSymbol: {ThreadpoolCallbackSymbol, "thread pool callback symbol", params.UnicodeString, []string{"threadpool.callback.symbol = 'RtlDestroyQueryDebugBuffer'"}, nil, nil}, - ThreadpoolCallbackModule: {ThreadpoolCallbackModule, "thread pool module containing the callback symbol", params.UnicodeString, []string{"threadpool.callback.module contains 'ntdll.dll'"}, nil, nil}, - ThreadpoolCallbackContext: {ThreadpoolCallbackContext, "thread pool callback context address", params.Address, []string{"threadpool.callback.context = '1df41e07bd0'"}, nil, nil}, - ThreadpoolCallbackContextRip: {ThreadpoolCallbackContextRip, "thread pool callback thread context instruction pointer", params.Address, []string{"threadpool.callback.context.rip = '1df42ffc1f8'"}, nil, nil}, - ThreadpoolCallbackContextRipSymbol: {ThreadpoolCallbackContextRipSymbol, "thread pool callback thread context instruction pointer symbol", params.UnicodeString, []string{"threadpool.callback.context.rip.symbol = 'VirtualProtect'"}, nil, nil}, - ThreadpoolCallbackContextRipModule: {ThreadpoolCallbackContextRipModule, "thread pool callback thread context instruction pointer symbol module", params.UnicodeString, []string{"threadpool.callback.context.rip.module contains 'ntdll.dll'"}, nil, nil}, - ThreadpoolSubprocessTag: {ThreadpoolSubprocessTag, "thread pool service identifier", params.Address, []string{"threadpool.subprocess_tag = '10d'"}, nil, nil}, - ThreadpoolTimerDuetime: {ThreadpoolTimerDuetime, "thread pool timer due time", params.Uint64, []string{"threadpool.timer.duetime > 10"}, nil, nil}, - ThreadpoolTimerSubqueue: {ThreadpoolTimerSubqueue, "thread pool timer subqueue address", params.Address, []string{"threadpool.timer.subqueue = '1db401703e8'"}, nil, nil}, - ThreadpoolTimer: {ThreadpoolTimer, "thread pool timer address", params.Address, []string{"threadpool.timer.address = '3e8'"}, nil, nil}, - ThreadpoolTimerPeriod: {ThreadpoolTimerPeriod, "thread pool timer period", params.Uint32, []string{"threadpool.timer.period = 0'"}, nil, nil}, - ThreadpoolTimerWindow: {ThreadpoolTimerWindow, "thread pool timer tolerate period", params.Uint32, []string{"threadpool.timer.window = 0'"}, nil, nil}, - ThreadpoolTimerAbsolute: {ThreadpoolTimerAbsolute, "indicates if the thread pool timer is absolute or relative", params.Bool, []string{"threadpool.timer.is_absolute = true'"}, nil, nil}, -} - -// ArgumentOf returns argument data for the specified field. -func ArgumentOf(name string) *Argument { - f, ok := fields[Field(name)] - if !ok { - // this can happen for pseudo fields - return nil - } - return f.Argument -} - -// IsField returns true if the provided string is a -// recognized field or pseudo field. Otherwise, it -// returns false. -func IsField(name string) bool { - if _, ok := fields[Field(name)]; ok || IsPseudoField(Field(name)) { - return true - } - return false -} From 51c4d1ff9bbcf3ed328c61ced5132cac4c1a4b28 Mon Sep 17 00:00:00 2001 From: Mostafa Moradian Date: Sat, 8 Aug 2026 20:50:04 +0200 Subject: [PATCH 14/28] feat(event): Add Linux event helpers and parameter formatting Provide Linux implementations for event helpers, parameter construction/formatting, callstack basics, and PE section stubs so shared packages compile without the Windows ETW path. --- pkg/callstack/callstack_linux.go | 46 ++++++++++- pkg/event/event_linux.go | 94 ++++++++++++++++++++++ pkg/event/event_linux_test.go | 46 +++++++++++ pkg/event/formatter_linux.go | 73 +++++++++++++++++ pkg/event/marshaller_linux.go | 34 ++++++++ pkg/event/param.go | 50 ------------ pkg/event/param_capture_linux.go | 29 +++++++ pkg/event/param_capture_windows.go | 75 +++++++++++++++++ pkg/event/param_linux.go | 125 +++++++++++++++++++++++++++++ pkg/event/stackwalk_linux.go | 36 +++++++++ pkg/event/types_linux.go | 13 +++ pkg/pe/types_linux.go | 36 +++++++++ 12 files changed, 606 insertions(+), 51 deletions(-) create mode 100644 pkg/event/event_linux.go create mode 100644 pkg/event/event_linux_test.go create mode 100644 pkg/event/formatter_linux.go create mode 100644 pkg/event/marshaller_linux.go create mode 100644 pkg/event/param_capture_linux.go create mode 100644 pkg/event/param_capture_windows.go create mode 100644 pkg/event/param_linux.go create mode 100644 pkg/event/stackwalk_linux.go create mode 100644 pkg/pe/types_linux.go diff --git a/pkg/callstack/callstack_linux.go b/pkg/callstack/callstack_linux.go index b333f77f2..268634821 100644 --- a/pkg/callstack/callstack_linux.go +++ b/pkg/callstack/callstack_linux.go @@ -20,8 +20,52 @@ package callstack +import "strings" + +// Callstack is a sequence of stack frames. type Callstack []Frame +// Frame describes a single stack frame. type Frame struct { - PID uint32 + PID uint32 + Addr uint64 + Symbol string + Module string +} + +func (s *Callstack) Init(n int) { + *s = make(Callstack, 0, n) +} + +func (s *Callstack) PushFrame(f Frame) { + *s = append(*s, f) +} + +func (s *Callstack) FrameAt(i int) Frame { + if i < 0 || i >= len(*s) { + return Frame{} + } + return (*s)[i] +} + +func (s *Callstack) Depth() int { return len(*s) } + +func (s *Callstack) IsEmpty() bool { return s.Depth() == 0 } + +func (s Callstack) String() string { + if len(s) == 0 { + return "" + } + parts := make([]string, 0, len(s)) + for _, f := range s { + if f.Symbol != "" { + parts = append(parts, f.Symbol) + continue + } + parts = append(parts, f.Module) + } + return strings.Join(parts, " < ") } + +// Colorize returns a plain string representation on Linux. +func (s Callstack) Colorize() string { return s.String() } diff --git a/pkg/event/event_linux.go b/pkg/event/event_linux.go new file mode 100644 index 000000000..ff1ecad48 --- /dev/null +++ b/pkg/event/event_linux.go @@ -0,0 +1,94 @@ +//go:build linux + +/* + * Copyright 2026 by Nedim Sabic Sabic + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package event + +import ( + "encoding/json" + "fmt" + + capver "github.com/rabbitstack/fibratus/pkg/cap/version" +) + +func (e *Event) IsCreateFile() bool { return false } +func (e *Event) IsCreateProcess() bool { return e.Type == CreateProcess || e.Type == Execve || e.Type == Clone } +func (e *Event) IsCreateProcessInternal() bool { return false } +func (e *Event) IsCreateThread() bool { return false } +func (e *Event) IsCloseFile() bool { return false } +func (e *Event) IsCreateHandle() bool { return false } +func (e *Event) IsCloseHandle() bool { return false } +func (e *Event) IsDeleteFile() bool { return false } +func (e *Event) IsRenameFile() bool { return false } +func (e *Event) IsEnumDirectory() bool { return false } +func (e *Event) IsTerminateProcess() bool { return e.Type == TerminateProcess || e.Type == Exit } +func (e *Event) IsTerminateThread() bool { return false } +func (e *Event) IsUnloadModule() bool { return false } +func (e *Event) IsLoadModule() bool { return false } +func (e *Event) IsLoadModuleInternal() bool { return false } +func (e *Event) IsModuleRundown() bool { return false } +func (e *Event) IsFileOpEnd() bool { return false } +func (e *Event) IsRegSetValue() bool { return false } +func (e *Event) IsRegSetValueInternal() bool { return false } +func (e *Event) IsRegCreateKey() bool { return false } +func (e *Event) IsProcessRundown() bool { return e.Type == ProcessRundown } +func (e *Event) IsProcessRundownInternal() bool { return false } +func (e *Event) IsVirtualAlloc() bool { return false } +func (e *Event) IsMapViewFile() bool { return false } +func (e *Event) IsUnmapViewFile() bool { return false } +func (e *Event) IsStackWalk() bool { return false } +func (e *Event) IsOpenThread() bool { return false } +func (e *Event) IsOpenProcess() bool { return false } +func (e *Event) IsNetworkTCP() bool { return false } +func (e *Event) IsNetworkUDP() bool { return false } +func (e *Event) IsDNS() bool { return false } +func (e *Event) IsRundown() bool { return e.IsProcessRundown() } +func (e *Event) IsSuccess() bool { return true } +func (e *Event) IsRundownProcessed() bool { return false } +func (e *Event) IsCreateDisposition() bool { return false } +func (e *Event) IsOverwriteDisposition() bool { return false } +func (e *Event) IsOpenDisposition() bool { return false } +func (e *Event) IsCreateRemoteThread() bool { return false } +func (e *Event) IsSurrogateProcess() bool { return false } +func (e *Event) IsSystemPid() bool { return e.PID == 0 || e.PID == 1 } +func (e *Event) IsState() bool { return e.Type.OnlyState() } + +// PartialKey returns a key used to deduplicate sequence partials. +// On Linux this combines the event type with the process identifier. +func (e *Event) PartialKey() uint64 { + return uint64(e.Type)<<32 | uint64(e.PID) +} + +// HookID returns the stable bitset index for this type. +func (t Type) HookID() uint16 { return uint16(t) } + +// MarshalJSON serializes the event to JSON. +func (e *Event) MarshalJSON() []byte { + b, err := json.Marshal(e) + if err != nil { + return []byte("{}") + } + return b +} + +// UnmarshalRaw recovers the event from a capture buffer. +// Captures are not wired on Linux yet. +func (e *Event) UnmarshalRaw(_ []byte, _ capver.Version) error { + return fmt.Errorf("event capture unmarshalling is not implemented on Linux") +} diff --git a/pkg/event/event_linux_test.go b/pkg/event/event_linux_test.go new file mode 100644 index 000000000..4365e32c6 --- /dev/null +++ b/pkg/event/event_linux_test.go @@ -0,0 +1,46 @@ +//go:build linux + +/* + * Copyright 2026 by Nedim Sabic Sabic + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package event + +import ( + "testing" + + "github.com/rabbitstack/fibratus/pkg/event/params" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestLinuxParamBasics(t *testing.T) { + p := NewParam(params.ProcessID, params.PID, uint32(42)) + require.NotNil(t, p) + assert.Equal(t, "42", p.String()) + + pars := Params{} + pars.Append(params.ProcessName, params.UnicodeString, "bash") + assert.Equal(t, "bash", pars.MustGetString(params.ProcessName)) +} + +func TestLinuxEventTypeHelpers(t *testing.T) { + e := &Event{Type: Execve, PID: 1} + assert.True(t, e.IsCreateProcess()) + assert.False(t, e.IsStackWalk()) + assert.Equal(t, uint16(Execve), e.Type.HookID()) +} diff --git a/pkg/event/formatter_linux.go b/pkg/event/formatter_linux.go new file mode 100644 index 000000000..720e3cf43 --- /dev/null +++ b/pkg/event/formatter_linux.go @@ -0,0 +1,73 @@ +//go:build linux + +/* + * Copyright 2026 by Nedim Sabic Sabic + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package event + +import "strconv" + +// Format applies the template on the provided event. +func (f *Formatter) Format(evt *Event) []byte { + if evt == nil { + return []byte{} + } + values := map[string]interface{}{ + ts: evt.Timestamp.String(), + pid: strconv.FormatUint(uint64(evt.PID), 10), + tid: strconv.FormatUint(uint64(evt.Tid), 10), + seq: strconv.FormatUint(evt.Seq, 10), + cpu: strconv.FormatUint(uint64(evt.CPU), 10), + typ: evt.Name, + cat: evt.Category, + desc: evt.Description, + host: evt.Host, + meta: evt.Metadata.String(), + parameters: evt.Params.String(), + } + + ps := evt.PS + if ps != nil { + values[proc] = ps.Name + values[ppid] = strconv.FormatUint(uint64(ps.Ppid), 10) + values[cwd] = ps.Cwd + values[exe] = ps.Exe + values[cmd] = ps.Cmdline + values[sid] = ps.SID + parent := ps.Parent + if parent != nil { + values[pproc] = parent.Name + values[pexe] = parent.Exe + values[pcmd] = parent.Cmdline + } + if ps.PE != nil { + values[pe] = ps.PE.String() + } + } + if !evt.Callstack.IsEmpty() { + values[cstack] = evt.Callstack.String() + } + + if f.expandParamsDot { + for _, par := range evt.Params { + values[".Params."+caser.String(par.Name)] = par.String() + } + } + + return f.t.ExecuteString(values) +} diff --git a/pkg/event/marshaller_linux.go b/pkg/event/marshaller_linux.go new file mode 100644 index 000000000..b187ec12e --- /dev/null +++ b/pkg/event/marshaller_linux.go @@ -0,0 +1,34 @@ +//go:build linux + +/* + * Copyright 2026 by Nedim Sabic Sabic + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package event + +var ( + // SerializeHandles indicates if handles are serialized as part of the process state + SerializeHandles bool + // SerializeThreads indicates if threads are serialized as part of the process state + SerializeThreads bool + // SerializeModules indicates if modules are serialized as part of the process state + SerializeModules bool + // SerializePE indicates if PE metadata are serialized as part of the process state + SerializePE bool + // SerializeEnvs indicates if the environment variables are serialized as part of the process state + SerializeEnvs bool +) diff --git a/pkg/event/param.go b/pkg/event/param.go index 58f003865..ec0a9ba9f 100644 --- a/pkg/event/param.go +++ b/pkg/event/param.go @@ -26,10 +26,7 @@ import ( "strings" "time" - "github.com/rabbitstack/fibratus/pkg/fs" - "github.com/rabbitstack/fibratus/pkg/network" "github.com/rabbitstack/fibratus/pkg/util/colorizer" - "github.com/rabbitstack/fibratus/pkg/util/key" "github.com/rabbitstack/fibratus/pkg/util/ntstatus" "github.com/rabbitstack/fibratus/pkg/util/va" "golang.org/x/text/cases" @@ -125,53 +122,6 @@ func (p Param) CaptureType() params.Type { // Params is the type that represents the sequence of event parameters type Params map[string]*Param -// NewParamFromCapture builds a parameter instance from the restored capture state. -func NewParamFromCapture(name string, typ params.Type, value params.Value, etype Type) *Param { - var enum ParamEnum - var flags ParamFlags - switch name { - case params.FileOperation: - enum = fs.FileCreateDispositions - case params.FileCreateOptions: - flags = FileCreateOptionsFlags - case params.FileAttributes: - flags = FileAttributeFlags - case params.FileShareMask: - flags = FileShareModeFlags - case params.FileInfoClass: - enum = fs.FileInfoClasses - case params.FileType: - enum = fs.FileTypes - case params.NetL4Proto: - enum = network.ProtoNames - case params.RegValueType: - enum = key.RegistryValueTypes - case params.MemAllocType: - flags = MemAllocationFlags - case params.FileViewSectionType: - enum = ViewSectionTypes - case params.DNSOpts: - flags = DNSOptsFlags - case params.DNSRR: - enum = DNSRecordTypes - case params.DNSRcode: - enum = DNSResponseCodes - case params.DesiredAccess: - if etype == OpenProcess { - flags = PsAccessRightFlags - } else { - flags = ThreadAccessRightFlags - } - case params.MemProtect: - if etype == VirtualAlloc || etype == VirtualFree { - flags = MemProtectionFlags - } else { - flags = ViewProtectionFlags - } - } - return &Param{Name: name, Type: typ, Value: value, Enum: enum, Flags: flags} -} - // Append adds a new parameter with the specified name, type and value. func (pars Params) Append(name string, typ params.Type, value params.Value, opts ...ParamOption) Params { pars[name] = NewParam(name, typ, value, opts...) diff --git a/pkg/event/param_capture_linux.go b/pkg/event/param_capture_linux.go new file mode 100644 index 000000000..b55f892e9 --- /dev/null +++ b/pkg/event/param_capture_linux.go @@ -0,0 +1,29 @@ +//go:build linux + +/* + * Copyright 2026 by Nedim Sabic Sabic + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package event + +import "github.com/rabbitstack/fibratus/pkg/event/params" + +// NewParamFromCapture builds a parameter instance from the restored capture state. +// Captures are not wired on Linux yet, so enrichment is deferred. +func NewParamFromCapture(name string, typ params.Type, value params.Value, _ Type) *Param { + return &Param{Name: name, Type: typ, Value: value} +} diff --git a/pkg/event/param_capture_windows.go b/pkg/event/param_capture_windows.go new file mode 100644 index 000000000..e64a44002 --- /dev/null +++ b/pkg/event/param_capture_windows.go @@ -0,0 +1,75 @@ +//go:build windows + +/* + * Copyright 2019-2020 by Nedim Sabic Sabic + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package event + +import ( + "github.com/rabbitstack/fibratus/pkg/event/params" + "github.com/rabbitstack/fibratus/pkg/fs" + "github.com/rabbitstack/fibratus/pkg/network" + "github.com/rabbitstack/fibratus/pkg/util/key" +) + +// NewParamFromCapture builds a parameter instance from the restored capture state. +func NewParamFromCapture(name string, typ params.Type, value params.Value, etype Type) *Param { + var enum ParamEnum + var flags ParamFlags + switch name { + case params.FileOperation: + enum = fs.FileCreateDispositions + case params.FileCreateOptions: + flags = FileCreateOptionsFlags + case params.FileAttributes: + flags = FileAttributeFlags + case params.FileShareMask: + flags = FileShareModeFlags + case params.FileInfoClass: + enum = fs.FileInfoClasses + case params.FileType: + enum = fs.FileTypes + case params.NetL4Proto: + enum = network.ProtoNames + case params.RegValueType: + enum = key.RegistryValueTypes + case params.MemAllocType: + flags = MemAllocationFlags + case params.FileViewSectionType: + enum = ViewSectionTypes + case params.DNSOpts: + flags = DNSOptsFlags + case params.DNSRR: + enum = DNSRecordTypes + case params.DNSRcode: + enum = DNSResponseCodes + case params.DesiredAccess: + if etype == OpenProcess { + flags = PsAccessRightFlags + } else { + flags = ThreadAccessRightFlags + } + case params.MemProtect: + if etype == VirtualAlloc || etype == VirtualFree { + flags = MemProtectionFlags + } else { + flags = ViewProtectionFlags + } + } + return &Param{Name: name, Type: typ, Value: value, Enum: enum, Flags: flags} +} diff --git a/pkg/event/param_linux.go b/pkg/event/param_linux.go new file mode 100644 index 000000000..9c80d5a05 --- /dev/null +++ b/pkg/event/param_linux.go @@ -0,0 +1,125 @@ +//go:build linux + +/* + * Copyright 2026 by Nedim Sabic Sabic + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package event + +import ( + "fmt" + "net" + "strconv" + "strings" + "time" + + "github.com/rabbitstack/fibratus/pkg/event/params" + "github.com/rabbitstack/fibratus/pkg/util/ntstatus" + "github.com/rabbitstack/fibratus/pkg/util/va" +) + +// NewParam creates a new event parameter. +func NewParam(name string, typ params.Type, value params.Value, options ...ParamOption) *Param { + var opts paramOpts + for _, opt := range options { + opt(&opts) + } + return &Param{Name: name, Type: typ, Value: value, Flags: opts.flags, Enum: opts.enum} +} + +// String returns the string representation of the parameter value. +func (p Param) String() string { + if p.Value == nil { + return "" + } + switch p.Type { + case params.UnicodeString, params.AnsiString, params.Path, params.DOSPath, params.Key, params.HandleType: + if s, ok := p.Value.(string); ok { + return s + } + return fmt.Sprintf("%v", p.Value) + case params.Status: + v, ok := p.Value.(uint32) + if !ok { + return "" + } + return ntstatus.FormatMessage(v) + case params.Address: + v, ok := p.Value.(uint64) + if !ok { + return "" + } + return va.Address(v).String() + case params.Int8: + return strconv.Itoa(int(p.Value.(int8))) + case params.Uint8: + return strconv.Itoa(int(p.Value.(uint8))) + case params.Int16: + return strconv.Itoa(int(p.Value.(int16))) + case params.Uint16, params.Port: + return strconv.Itoa(int(p.Value.(uint16))) + case params.Uint32, params.PID, params.TID: + return strconv.Itoa(int(p.Value.(uint32))) + case params.Int32: + return strconv.Itoa(int(p.Value.(int32))) + case params.Uint64: + return strconv.FormatUint(p.Value.(uint64), 10) + case params.Int64: + return strconv.Itoa(int(p.Value.(int64))) + case params.IPv4, params.IPv6: + return p.Value.(net.IP).String() + case params.Bool: + return strconv.FormatBool(p.Value.(bool)) + case params.Float: + return strconv.FormatFloat(float64(p.Value.(float32)), 'f', 6, 32) + case params.Double: + return strconv.FormatFloat(p.Value.(float64), 'f', 6, 64) + case params.Time: + return p.Value.(time.Time).String() + case params.Enum: + if p.Enum == nil { + return "" + } + v, ok := p.Value.(uint32) + if !ok { + return "" + } + return p.Enum[v] + case params.Flags, params.Flags64: + if p.Flags == nil { + return "" + } + switch v := p.Value.(type) { + case uint32: + return p.Flags.String(uint64(v)) + case uint64: + return p.Flags.String(v) + default: + return "" + } + case params.Slice: + switch slice := p.Value.(type) { + case []string: + return strings.Join(slice, ",") + default: + return fmt.Sprintf("%v", slice) + } + case params.Binary: + return string(p.Value.([]byte)) + } + return fmt.Sprintf("%v", p.Value) +} diff --git a/pkg/event/stackwalk_linux.go b/pkg/event/stackwalk_linux.go new file mode 100644 index 000000000..0f92b68fe --- /dev/null +++ b/pkg/event/stackwalk_linux.go @@ -0,0 +1,36 @@ +//go:build linux + +/* + * Copyright 2026 by Nedim Sabic Sabic + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package event + +// StackwalkDecorator is a no-op on Linux. Callstack enrichment +// via StackWalk events is a Windows ETW concept. +type StackwalkDecorator struct{} + +// NewStackwalkDecorator constructs a no-op stackwalk decorator. +func NewStackwalkDecorator(_ *Queue) *StackwalkDecorator { + return &StackwalkDecorator{} +} + +func (s *StackwalkDecorator) Push(_ *Event) {} + +func (s *StackwalkDecorator) Pop(e *Event) *Event { return e } + +func (s *StackwalkDecorator) Stop() {} diff --git a/pkg/event/types_linux.go b/pkg/event/types_linux.go index 91ef4be20..60af41af5 100644 --- a/pkg/event/types_linux.go +++ b/pkg/event/types_linux.go @@ -42,6 +42,19 @@ const ( Exit ProcessRundown Clone + + // Windows-only event types stubbed so shared consumers (rules compiler) + // compile on Linux. These are never emitted by the Linux event source. + RegOpenKey + OpenThread + OpenProcess + SetFileInformation + CreateFile + MapViewFile + UnmapViewFile + SetThreadContext + CreateSymbolicLinkObject + CreateThread ) func (t Type) String() string { diff --git a/pkg/pe/types_linux.go b/pkg/pe/types_linux.go new file mode 100644 index 000000000..783d077be --- /dev/null +++ b/pkg/pe/types_linux.go @@ -0,0 +1,36 @@ +//go:build linux + +/* + * Copyright 2026 by Nedim Sabic Sabic + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package pe + +import "fmt" + +// Sec contains section attributes. On Linux this is only used so +// shared filter foreach helpers can compile against pe.Sec. +type Sec struct { + Name string + Size uint32 + Entropy float64 + Md5 string +} + +func (s Sec) String() string { + return fmt.Sprintf("Name: %s, Size: %d, Entropy: %f, Md5: %s", s.Name, s.Size, s.Entropy, s.Md5) +} From 45d7b590be507e2d87ecdd99d052a67ad7d332e7 Mon Sep 17 00:00:00 2001 From: Mostafa Moradian Date: Sat, 8 Aug 2026 20:50:09 +0200 Subject: [PATCH 15/28] feat(ps): Implement LinuxSnapshotter and ProcessKey Add the in-memory Linux process snapshotter, ProcessKey identity, and PS fields needed by shared formatters and filter foreach helpers. --- pkg/ps/process_key.go | 25 +++++ pkg/ps/snapshotter_linux.go | 151 +++++++++++++++++++++++++++++++ pkg/ps/snapshotter_linux_test.go | 48 ++++++++++ pkg/ps/types/types_linux.go | 39 ++++++-- 4 files changed, 255 insertions(+), 8 deletions(-) create mode 100644 pkg/ps/process_key.go create mode 100644 pkg/ps/snapshotter_linux.go create mode 100644 pkg/ps/snapshotter_linux_test.go diff --git a/pkg/ps/process_key.go b/pkg/ps/process_key.go new file mode 100644 index 000000000..0834f50aa --- /dev/null +++ b/pkg/ps/process_key.go @@ -0,0 +1,25 @@ +/* + * Copyright 2026 by Nedim Sabic Sabic + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ps + +// ProcessKey uniquely identifies a process instance across PID reuse. +type ProcessKey struct { + PID uint32 + StartBootTime uint64 +} diff --git a/pkg/ps/snapshotter_linux.go b/pkg/ps/snapshotter_linux.go new file mode 100644 index 000000000..10ca04fe4 --- /dev/null +++ b/pkg/ps/snapshotter_linux.go @@ -0,0 +1,151 @@ +//go:build linux + +/* + * Copyright 2026 by Nedim Sabic Sabic + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ps + +import ( + "sync" + + "github.com/rabbitstack/fibratus/pkg/event" + pstypes "github.com/rabbitstack/fibratus/pkg/ps/types" + "github.com/rabbitstack/fibratus/pkg/util/va" +) + +// LinuxSnapshotter stores Linux process state for enrichment and rule evaluation. +type LinuxSnapshotter interface { + Resolver + Write(*event.Event) error + Remove(*event.Event) error + UpsertSnapshot(*pstypes.PS) + Put(*pstypes.PS) + Size() uint32 + Close() error + AddThread(*event.Event) error + RemoveThread(pid uint32, tid uint32) error + AddMmap(*event.Event) error + RemoveMmap(pid uint32, addr va.Address) error +} + +type linuxSnapshotter struct { + mu sync.RWMutex + procs map[uint32]*pstypes.PS +} + +// NewLinuxSnapshotter builds an in-memory Linux process snapshotter. +func NewLinuxSnapshotter() LinuxSnapshotter { + return &linuxSnapshotter{procs: make(map[uint32]*pstypes.PS)} +} + +func (s *linuxSnapshotter) Find(pid uint32) (bool, *pstypes.PS) { + s.mu.RLock() + defer s.mu.RUnlock() + ps, ok := s.procs[pid] + return ok, ps +} + +func (s *linuxSnapshotter) Put(ps *pstypes.PS) { + if ps == nil { + return + } + s.mu.Lock() + defer s.mu.Unlock() + s.procs[ps.PID] = ps +} + +func (s *linuxSnapshotter) UpsertSnapshot(ps *pstypes.PS) { + s.Put(ps) +} + +func (s *linuxSnapshotter) Write(evt *event.Event) error { + if evt == nil || evt.PS == nil { + return nil + } + s.Put(evt.PS) + return nil +} + +func (s *linuxSnapshotter) Remove(evt *event.Event) error { + if evt == nil { + return nil + } + s.mu.Lock() + defer s.mu.Unlock() + delete(s.procs, evt.PID) + return nil +} + +func (s *linuxSnapshotter) Size() uint32 { + s.mu.RLock() + defer s.mu.RUnlock() + return uint32(len(s.procs)) +} + +func (s *linuxSnapshotter) Close() error { + s.mu.Lock() + defer s.mu.Unlock() + s.procs = make(map[uint32]*pstypes.PS) + return nil +} + +func (s *linuxSnapshotter) AddThread(evt *event.Event) error { + if evt == nil || evt.PS == nil { + return nil + } + ok, ps := s.Find(evt.PID) + if !ok || ps == nil { + s.Put(evt.PS) + return nil + } + ps.AddThread(pstypes.Thread{Tid: evt.Tid, Pid: evt.PID}) + return nil +} + +func (s *linuxSnapshotter) RemoveThread(pid uint32, tid uint32) error { + ok, ps := s.Find(pid) + if !ok || ps == nil { + return nil + } + ps.RemoveThread(tid) + return nil +} + +func (s *linuxSnapshotter) AddMmap(evt *event.Event) error { + if evt == nil || evt.PS == nil { + return nil + } + ok, ps := s.Find(evt.PID) + if !ok || ps == nil { + s.Put(evt.PS) + return nil + } + for _, mmap := range evt.PS.Mmaps { + ps.AddMmap(mmap) + } + return nil +} + +func (s *linuxSnapshotter) RemoveMmap(pid uint32, addr va.Address) error { + ok, ps := s.Find(pid) + if !ok || ps == nil { + return nil + } + ps.RemoveMmap(addr) + return nil +} diff --git a/pkg/ps/snapshotter_linux_test.go b/pkg/ps/snapshotter_linux_test.go new file mode 100644 index 000000000..6638ed6a7 --- /dev/null +++ b/pkg/ps/snapshotter_linux_test.go @@ -0,0 +1,48 @@ +//go:build linux + +/* + * Copyright 2026 by Nedim Sabic Sabic + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ps + +import ( + "testing" + + "github.com/rabbitstack/fibratus/pkg/event" + pstypes "github.com/rabbitstack/fibratus/pkg/ps/types" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestLinuxSnapshotterFindPut(t *testing.T) { + s := NewLinuxSnapshotter() + ps := &pstypes.PS{PID: 100, Name: "bash", StartBootTime: 1234} + s.Put(ps) + + ok, got := s.Find(100) + require.True(t, ok) + assert.Equal(t, "bash", got.Name) + assert.Equal(t, uint32(1), s.Size()) + + require.NoError(t, s.Write(&event.Event{PID: 200, PS: &pstypes.PS{PID: 200, Name: "sh"}})) + assert.Equal(t, uint32(2), s.Size()) + + require.NoError(t, s.Remove(&event.Event{PID: 100})) + ok, _ = s.Find(100) + assert.False(t, ok) +} diff --git a/pkg/ps/types/types_linux.go b/pkg/ps/types/types_linux.go index 138ef02f8..8c6ffc906 100644 --- a/pkg/ps/types/types_linux.go +++ b/pkg/ps/types/types_linux.go @@ -29,6 +29,13 @@ import ( "github.com/rabbitstack/fibratus/pkg/util/va" ) +// PE is a placeholder for PE metadata on Linux builds. +// Linux process images are ELF; this field exists so shared +// formatters/templates compile without Windows PE types. +type PE struct{} + +func (p *PE) String() string { return "" } + type PS struct { sync.RWMutex PID uint32 `json:"pid"` @@ -42,12 +49,22 @@ type PS struct { StartBootTime uint64 `json:"start_boot_time"` UID uint32 `json:"uid"` GID uint32 `json:"gid"` - Username string `json:"username"` - Envs map[string]string `json:"envs"` - Parent *PS `json:"parent"` - Threads map[uint32]Thread `json:"-"` - Mmaps []Mmap `json:"mmaps"` - Modules []Module `json:"modules"` + Username string `json:"username"` + Domain string `json:"domain"` + SID string `json:"sid"` + SessionID uint32 `json:"session_id"` + TokenIntegrityLevel string `json:"token_integrity_level"` + TokenElevationType string `json:"token_elevation_type"` + IsTokenElevated bool `json:"is_token_elevated"` + IsWOW64 bool `json:"is_wow_64"` + IsPackaged bool `json:"is_packaged"` + IsProtected bool `json:"is_protected"` + Envs map[string]string `json:"envs"` + Parent *PS `json:"parent"` + Threads map[uint32]Thread `json:"-"` + Mmaps []Mmap `json:"mmaps"` + Modules []Module `json:"modules"` + PE *PE `json:"-"` } func (ps *PS) String() string { @@ -67,14 +84,20 @@ func (ps *PS) Ancestors() []string { } type Thread struct { - Tid uint32 - Pid uint32 + Tid uint32 + Pid uint32 + StartAddress va.Address + UstackBase va.Address + UstackLimit va.Address + KstackBase va.Address + KstackLimit va.Address } type Module struct { Name string BaseAddress va.Address Size uint64 + Checksum uint32 } type Mmap struct { From 6846271bf8f7426c14507ed8d41426855f17dcfc Mon Sep 17 00:00:00 2001 From: Mostafa Moradian Date: Sat, 8 Aug 2026 20:50:10 +0200 Subject: [PATCH 16/28] refactor(rules): Migrate shared consumers to ps.Resolver Switch the rule engine, compiler, sequence state, and filter options to the narrow Resolver interface, and add Linux filter/action stubs so rules compile and evaluate on Linux. --- pkg/filter/accessor.go | 82 +------------- pkg/filter/accessor_linux.go | 117 ++++++++++++++++++++ pkg/filter/accessor_narrow_linux.go | 42 +++++++ pkg/filter/accessor_narrow_windows.go | 104 +++++++++++++++++ pkg/filter/accessor_stubs_linux.go | 46 ++++++++ pkg/filter/accessor_windows.go | 4 +- pkg/filter/filter_linux.go | 110 ++++++++++++++++++ pkg/filter/filter_windows.go | 6 +- pkg/filter/ql/function.go | 89 +-------------- pkg/filter/ql/function_callstack_linux.go | 53 +++++++++ pkg/filter/ql/function_callstack_windows.go | 117 ++++++++++++++++++++ pkg/filter/ql/functions/minidump_linux.go | 39 +++++++ pkg/rules/action/isolate_linux.go | 32 ++++++ pkg/rules/action/kill_linux.go | 29 +++++ pkg/rules/compiler.go | 4 +- pkg/rules/engine.go | 4 +- pkg/rules/engine_linux_test.go | 36 ++++++ pkg/rules/sequence.go | 4 +- 18 files changed, 740 insertions(+), 178 deletions(-) create mode 100644 pkg/filter/accessor_linux.go create mode 100644 pkg/filter/accessor_narrow_linux.go create mode 100644 pkg/filter/accessor_narrow_windows.go create mode 100644 pkg/filter/accessor_stubs_linux.go create mode 100644 pkg/filter/filter_linux.go create mode 100644 pkg/filter/ql/function_callstack_linux.go create mode 100644 pkg/filter/ql/function_callstack_windows.go create mode 100644 pkg/filter/ql/functions/minidump_linux.go create mode 100644 pkg/rules/action/isolate_linux.go create mode 100644 pkg/rules/action/kill_linux.go create mode 100644 pkg/rules/engine_linux_test.go diff --git a/pkg/filter/accessor.go b/pkg/filter/accessor.go index 470f636ff..3362bdda3 100644 --- a/pkg/filter/accessor.go +++ b/pkg/filter/accessor.go @@ -152,87 +152,7 @@ func (*evtAccessor) Get(f Field, evt *event.Event) (params.Value, error) { // as a regular LHS/RHS component, used as a function parameter or // referenced in the bound field. func (f *filter) narrowAccessors() { - var ( - removeEvtAccessor = true - removePsAccessor = true - removeThreadAccessor = true - removeModuleAccessor = true - removeFileAccessor = true - removeRegistryAccessor = true - removeNetworkAccessor = true - removeHandleAccessor = true - removePEAccessor = true - removeMemAccessor = true - removeDNSAccessor = true - removeThreadpoolAccessor = true - ) - - for _, field := range f.fields { - switch { - case field.Name.IsEvtField() || field.Name.IsKevtField(): - removeEvtAccessor = false - case field.Name.IsPeField(): - removePEAccessor = false - case field.Name.IsPsField(): - removePsAccessor = false - case field.Name.IsThreadField(): - removeThreadAccessor = false - case field.Name.IsImageField() || field.Name.IsModuleField(): - removeModuleAccessor = false - case field.Name.IsFileField(): - removeFileAccessor = false - case field.Name.IsRegistryField(): - removeRegistryAccessor = false - case field.Name.IsNetworkField(): - removeNetworkAccessor = false - case field.Name.IsHandleField(): - removeHandleAccessor = false - case field.Name.IsMemField(): - removeMemAccessor = false - case field.Name.IsDNSField(): - removeDNSAccessor = false - case field.Name.IsThreadpoolField(): - removeThreadpoolAccessor = false - } - } - - if removeEvtAccessor { - f.removeAccessor(&evtAccessor{}) - } - if removePsAccessor { - f.removeAccessor(&psAccessor{}) - } - if removeThreadAccessor { - f.removeAccessor(&threadAccessor{}) - } - if removeModuleAccessor { - f.removeAccessor(&moduleAccessor{}) - } - if removeFileAccessor { - f.removeAccessor(&fileAccessor{}) - } - if removeRegistryAccessor { - f.removeAccessor(®istryAccessor{}) - } - if removeNetworkAccessor { - f.removeAccessor(&networkAccessor{}) - } - if removeHandleAccessor { - f.removeAccessor(&handleAccessor{}) - } - if removePEAccessor { - f.removeAccessor(&peAccessor{}) - } - if removeMemAccessor { - f.removeAccessor(&memAccessor{}) - } - if removeDNSAccessor { - f.removeAccessor(&dnsAccessor{}) - } - if removeThreadpoolAccessor { - f.removeAccessor(&threadpoolAccessor{}) - } - + f.pruneUnusedAccessors() for _, accessor := range f.accessors { accessor.SetFields(f.fields) accessor.SetSegments(f.segments) diff --git a/pkg/filter/accessor_linux.go b/pkg/filter/accessor_linux.go new file mode 100644 index 000000000..b1aac733d --- /dev/null +++ b/pkg/filter/accessor_linux.go @@ -0,0 +1,117 @@ +//go:build linux + +/* + * Copyright 2026 by Nedim Sabic Sabic + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package filter + +import ( + "github.com/rabbitstack/fibratus/pkg/event" + "github.com/rabbitstack/fibratus/pkg/event/params" + "github.com/rabbitstack/fibratus/pkg/filter/fields" + "github.com/rabbitstack/fibratus/pkg/ps" +) + +// GetAccessors returns the accessors available on Linux. +func GetAccessors() []Accessor { + return []Accessor{ + newEventAccessor(), + newPSAccessor(nil), + } +} + +type psAccessor struct { + psnap ps.Resolver +} + +func (psAccessor) SetFields([]Field) {} +func (psAccessor) SetSegments([]fields.Segment) {} +func (psAccessor) IsFieldAccessible(e *event.Event) bool { + return e.PS != nil || e.Category == event.Process +} + +func newPSAccessor(psnap ps.Resolver) Accessor { return &psAccessor{psnap: psnap} } + +func (a *psAccessor) Get(f Field, e *event.Event) (params.Value, error) { + switch f.Name { + case fields.PsPid: + return e.PID, nil + case fields.PsPpid: + if e.PS == nil { + return nil, ErrPsNil + } + return e.PS.Ppid, nil + case fields.PsName: + if e.PS == nil { + return nil, ErrPsNil + } + return e.PS.Name, nil + case fields.PsComm, fields.PsCmdline: + if e.PS == nil { + return nil, ErrPsNil + } + return e.PS.Cmdline, nil + case fields.PsExe: + if e.PS == nil { + return nil, ErrPsNil + } + return e.PS.Exe, nil + case fields.PsArgs: + if e.PS == nil { + return nil, ErrPsNil + } + return e.PS.Args, nil + case fields.PsCwd: + if e.PS == nil { + return nil, ErrPsNil + } + return e.PS.Cwd, nil + case fields.PsUsername: + if e.PS == nil { + return nil, ErrPsNil + } + return e.PS.Username, nil + case fields.PsEnvs: + if e.PS == nil { + return nil, ErrPsNil + } + return e.PS.Envs, nil + case fields.PsParentPid: + if e.PS == nil || e.PS.Parent == nil { + return nil, ErrPsNil + } + return e.PS.Parent.PID, nil + case fields.PsParentName: + if e.PS == nil || e.PS.Parent == nil { + return nil, ErrPsNil + } + return e.PS.Parent.Name, nil + case fields.PsParentCmdline: + if e.PS == nil || e.PS.Parent == nil { + return nil, ErrPsNil + } + return e.PS.Parent.Cmdline, nil + case fields.PsParentExe: + if e.PS == nil || e.PS.Parent == nil { + return nil, ErrPsNil + } + return e.PS.Parent.Exe, nil + default: + return nil, nil + } +} diff --git a/pkg/filter/accessor_narrow_linux.go b/pkg/filter/accessor_narrow_linux.go new file mode 100644 index 000000000..187a7020e --- /dev/null +++ b/pkg/filter/accessor_narrow_linux.go @@ -0,0 +1,42 @@ +//go:build linux + +/* + * Copyright 2026 by Nedim Sabic Sabic + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package filter + +func (f *filter) pruneUnusedAccessors() { + removeEvtAccessor := true + removePsAccessor := true + + for _, field := range f.fields { + switch { + case field.Name.IsEvtField() || field.Name.IsKevtField(): + removeEvtAccessor = false + case field.Name.IsPsField(): + removePsAccessor = false + } + } + + if removeEvtAccessor { + f.removeAccessor(&evtAccessor{}) + } + if removePsAccessor { + f.removeAccessor(&psAccessor{}) + } +} diff --git a/pkg/filter/accessor_narrow_windows.go b/pkg/filter/accessor_narrow_windows.go new file mode 100644 index 000000000..0d1947f96 --- /dev/null +++ b/pkg/filter/accessor_narrow_windows.go @@ -0,0 +1,104 @@ +//go:build windows + +/* + * Copyright 2020-2021 by Nedim Sabic Sabic + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package filter + +func (f *filter) pruneUnusedAccessors() { + var ( + removeEvtAccessor = true + removePsAccessor = true + removeThreadAccessor = true + removeModuleAccessor = true + removeFileAccessor = true + removeRegistryAccessor = true + removeNetworkAccessor = true + removeHandleAccessor = true + removePEAccessor = true + removeMemAccessor = true + removeDNSAccessor = true + removeThreadpoolAccessor = true + ) + + for _, field := range f.fields { + switch { + case field.Name.IsEvtField() || field.Name.IsKevtField(): + removeEvtAccessor = false + case field.Name.IsPeField(): + removePEAccessor = false + case field.Name.IsPsField(): + removePsAccessor = false + case field.Name.IsThreadField(): + removeThreadAccessor = false + case field.Name.IsImageField() || field.Name.IsModuleField(): + removeModuleAccessor = false + case field.Name.IsFileField(): + removeFileAccessor = false + case field.Name.IsRegistryField(): + removeRegistryAccessor = false + case field.Name.IsNetworkField(): + removeNetworkAccessor = false + case field.Name.IsHandleField(): + removeHandleAccessor = false + case field.Name.IsMemField(): + removeMemAccessor = false + case field.Name.IsDNSField(): + removeDNSAccessor = false + case field.Name.IsThreadpoolField(): + removeThreadpoolAccessor = false + } + } + + if removeEvtAccessor { + f.removeAccessor(&evtAccessor{}) + } + if removePsAccessor { + f.removeAccessor(&psAccessor{}) + } + if removeThreadAccessor { + f.removeAccessor(&threadAccessor{}) + } + if removeModuleAccessor { + f.removeAccessor(&moduleAccessor{}) + } + if removeFileAccessor { + f.removeAccessor(&fileAccessor{}) + } + if removeRegistryAccessor { + f.removeAccessor(®istryAccessor{}) + } + if removeNetworkAccessor { + f.removeAccessor(&networkAccessor{}) + } + if removeHandleAccessor { + f.removeAccessor(&handleAccessor{}) + } + if removePEAccessor { + f.removeAccessor(&peAccessor{}) + } + if removeMemAccessor { + f.removeAccessor(&memAccessor{}) + } + if removeDNSAccessor { + f.removeAccessor(&dnsAccessor{}) + } + if removeThreadpoolAccessor { + f.removeAccessor(&threadpoolAccessor{}) + } +} diff --git a/pkg/filter/accessor_stubs_linux.go b/pkg/filter/accessor_stubs_linux.go new file mode 100644 index 000000000..a66afd9b4 --- /dev/null +++ b/pkg/filter/accessor_stubs_linux.go @@ -0,0 +1,46 @@ +//go:build linux + +/* + * Copyright 2026 by Nedim Sabic Sabic + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package filter + +import ( + "github.com/rabbitstack/fibratus/pkg/event" + "github.com/rabbitstack/fibratus/pkg/event/params" + "github.com/rabbitstack/fibratus/pkg/filter/fields" +) + +// noopAccessor satisfies Accessor for Windows-only field families on Linux. +type noopAccessor struct{} + +func (noopAccessor) Get(Field, *event.Event) (params.Value, error) { return nil, nil } +func (noopAccessor) SetFields([]Field) {} +func (noopAccessor) SetSegments([]fields.Segment) {} +func (noopAccessor) IsFieldAccessible(*event.Event) bool { return false } + +func newThreadAccessor() Accessor { return noopAccessor{} } +func newModuleAccessor() Accessor { return noopAccessor{} } +func newFileAccessor() Accessor { return noopAccessor{} } +func newRegistryAccessor() Accessor { return noopAccessor{} } +func newNetworkAccessor() Accessor { return noopAccessor{} } +func newHandleAccessor() Accessor { return noopAccessor{} } +func newPEAccessor() Accessor { return noopAccessor{} } +func newMemAccessor() Accessor { return noopAccessor{} } +func newDNSAccessor() Accessor { return noopAccessor{} } +func newThreadpoolAccessor() Accessor { return noopAccessor{} } diff --git a/pkg/filter/accessor_windows.go b/pkg/filter/accessor_windows.go index 25e60ee7e..79c1f0d4c 100644 --- a/pkg/filter/accessor_windows.go +++ b/pkg/filter/accessor_windows.go @@ -72,7 +72,7 @@ func getParentPs(e *event.Event) *pstypes.PS { // psAccessor extracts process's state or event specific values. type psAccessor struct { - psnap psnap.Snapshotter + psnap psnap.Resolver } func (psAccessor) SetFields([]Field) {} @@ -81,7 +81,7 @@ func (psAccessor) IsFieldAccessible(e *event.Event) bool { return e.PS != nil || e.Category == event.Process } -func newPSAccessor(psnap psnap.Snapshotter) Accessor { return &psAccessor{psnap: psnap} } +func newPSAccessor(psnap psnap.Resolver) Accessor { return &psAccessor{psnap: psnap} } func (ps *psAccessor) Get(f Field, e *event.Event) (params.Value, error) { switch f.Name { diff --git a/pkg/filter/filter_linux.go b/pkg/filter/filter_linux.go new file mode 100644 index 000000000..44179cbff --- /dev/null +++ b/pkg/filter/filter_linux.go @@ -0,0 +1,110 @@ +//go:build linux + +/* + * Copyright 2026 by Nedim Sabic Sabic + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package filter + +import ( + "fmt" + "strings" + + "github.com/rabbitstack/fibratus/pkg/config" + "github.com/rabbitstack/fibratus/pkg/filter/fields" + "github.com/rabbitstack/fibratus/pkg/filter/ql" + "github.com/rabbitstack/fibratus/pkg/ps" +) + +type opts struct { + psnap ps.Resolver +} + +// Option defines the option supplied to the filter +type Option func(o *opts) + +// WithPSnapshotter passes a process resolver reference to the filter. +func WithPSnapshotter(psnap ps.Resolver) Option { + return func(o *opts) { + o.psnap = psnap + } +} + +// New creates a new filter with the specified filter expression. +func New(expr string, config *config.Config, options ...Option) Filter { + var opts opts + for _, opt := range options { + opt(&opts) + } + accessors := []Accessor{ + newEventAccessor(), + newPSAccessor(opts.psnap), + } + + fconfig := config.Filters + + var parser *ql.Parser + if fconfig.HasMacros() { + parser = ql.NewParserWithConfig(expr, fconfig) + } else { + parser = ql.NewParser(expr) + } + + return &filter{ + parser: parser, + accessors: accessors, + fields: make([]Field, 0), + segments: make([]fields.Segment, 0), + stringFields: make(map[fields.Field][]string), + boundFields: make([]*ql.BoundFieldLiteral, 0), + seqBoundFields: make(map[int][]BoundField), + } +} + +// NewFromCLI builds and compiles a filter by joining all the command line arguments into the filter expression. +func NewFromCLI(args []string, config *config.Config) (Filter, error) { + expr := strings.Join(args, " ") + if expr == "" { + return nil, nil + } + filter := New(expr, config) + if err := filter.Compile(); err != nil { + return nil, fmt.Errorf("bad filter:\n%v", err) + } + return filter, nil +} + +// NewFromCLIWithAllAccessors builds and compiles a filter with all field accessors enabled. +func NewFromCLIWithAllAccessors(args []string) (Filter, error) { + expr := strings.Join(args, " ") + if expr == "" { + return nil, nil + } + filter := &filter{ + parser: ql.NewParser(expr), + accessors: GetAccessors(), + fields: make([]Field, 0), + segments: make([]fields.Segment, 0), + stringFields: make(map[fields.Field][]string), + boundFields: make([]*ql.BoundFieldLiteral, 0), + seqBoundFields: make(map[int][]BoundField), + } + if err := filter.Compile(); err != nil { + return nil, fmt.Errorf("bad filter:\n %v", err) + } + return filter, nil +} diff --git a/pkg/filter/filter_windows.go b/pkg/filter/filter_windows.go index d2a0ea1fa..ce36e657a 100644 --- a/pkg/filter/filter_windows.go +++ b/pkg/filter/filter_windows.go @@ -29,14 +29,14 @@ import ( ) type opts struct { - psnap ps.Snapshotter + psnap ps.Resolver } // Option defines the option supplied to the filter type Option func(o *opts) -// WithPSnapshotter passes a process snapshotter reference to the filter. -func WithPSnapshotter(psnap ps.Snapshotter) Option { +// WithPSnapshotter passes a process resolver reference to the filter. +func WithPSnapshotter(psnap ps.Resolver) Option { return func(o *opts) { o.psnap = psnap } diff --git a/pkg/filter/ql/function.go b/pkg/filter/ql/function.go index 332cd1232..733f4c405 100644 --- a/pkg/filter/ql/function.go +++ b/pkg/filter/ql/function.go @@ -30,8 +30,6 @@ import ( "github.com/rabbitstack/fibratus/pkg/filter/fields" "github.com/rabbitstack/fibratus/pkg/pe" pstypes "github.com/rabbitstack/fibratus/pkg/ps/types" - "github.com/rabbitstack/fibratus/pkg/util/signature" - "golang.org/x/sys/windows" "github.com/rabbitstack/fibratus/pkg/filter/ql/functions" ) @@ -246,40 +244,10 @@ func (f *Foreach) Call(args []interface{}) (interface{}, bool) { } } case callstack.Callstack: - var pid uint32 - var proc windows.Handle - var err error - - if !elems.IsEmpty() { - pid = elems.FrameAt(0).PID - } - - // open process handle with required access mask - var desiredAccess uint32 - loop: - for _, seg := range segments { - switch seg.Segment { - case fields.CallsiteLeadingAssemblySegment, fields.CallsiteTrailingAssemblySegment: - // break on broader access rights - desiredAccess = windows.PROCESS_QUERY_INFORMATION | windows.PROCESS_VM_READ - break loop - case fields.AllocationSizeSegment, fields.ProtectionSegment: - desiredAccess = windows.PROCESS_QUERY_INFORMATION - } - } - if desiredAccess != 0 { - proc, err = windows.OpenProcess(desiredAccess, false, pid) - if err != nil { - return false, false - } - defer windows.Close(proc) - } - - for _, frame := range elems { - if f.evalExpr(e, useCallValuer, f.callstackMapValuer(segments, frame, proc), valuer) { - return true, true - } + if ok, matched := f.foreachCallstack(elems, segments, e, useCallValuer, valuer); ok { + return matched, true } + return false, false } return false, false @@ -546,57 +514,6 @@ func (f *Foreach) mmapMapValuer(segments []*BoundSegmentLiteral, mmap pstypes.Mm return valuer } -// callstackMapValuer returns map valuer with thread stack frame data. -func (f *Foreach) callstackMapValuer(segments []*BoundSegmentLiteral, frame callstack.Frame, proc windows.Handle) MapValuer { - var valuer = MapValuer{} - for _, seg := range segments { - key := seg.Value - switch seg.Segment { - case fields.AddressSegment: - valuer[key] = frame.Addr.String() - case fields.OffsetSegment: - valuer[key] = frame.Offset - case fields.IsUnbackedSegment: - valuer[key] = frame.IsUnbacked() - case fields.ModuleSegment: - valuer[key] = frame.Module - case fields.SymbolSegment: - valuer[key] = frame.Module + "!" + frame.Symbol - case fields.AllocationSizeSegment: - valuer[key] = frame.AllocationSize(proc) - case fields.ProtectionSegment: - valuer[key] = frame.Protection(proc) - case fields.CallsiteTrailingAssemblySegment: - valuer[key] = frame.CallsiteAssembly(proc, false) - case fields.CallsiteLeadingAssemblySegment: - valuer[key] = frame.CallsiteAssembly(proc, true) - case fields.ModuleSignatureExistsSegment, fields.ModuleSignatureTrustedSegment, - fields.ModuleSignatureIssuerSegment, fields.ModuleSignatureSubjectSegment: - - sign := signature.GetSignatures().DoRequest(signature.MakeKey(frame.Module, 0, 0, 0)) - if sign == nil { - continue - } - - switch seg.Segment { - case fields.ModuleSignatureExistsSegment: - valuer[key] = sign.Exists() - case fields.ModuleSignatureTrustedSegment: - valuer[key] = sign.IsTrusted() - case fields.ModuleSignatureIssuerSegment: - if sign.HasCertificate() { - valuer[key] = sign.Cert().Issuer - } - case fields.ModuleSignatureSubjectSegment: - if sign.HasCertificate() { - valuer[key] = sign.Cert().Subject - } - } - } - } - return valuer -} - // sectionMapValuer returns map valuer with PE section data. func (f *Foreach) sectionMapValuer(segments []*BoundSegmentLiteral, section pe.Sec) MapValuer { var valuer = MapValuer{} diff --git a/pkg/filter/ql/function_callstack_linux.go b/pkg/filter/ql/function_callstack_linux.go new file mode 100644 index 000000000..1b618439a --- /dev/null +++ b/pkg/filter/ql/function_callstack_linux.go @@ -0,0 +1,53 @@ +//go:build linux + +/* + * Copyright 2026 by Nedim Sabic Sabic + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ql + +import ( + "fmt" + + "github.com/rabbitstack/fibratus/pkg/callstack" + "github.com/rabbitstack/fibratus/pkg/filter/fields" +) + +func (f *Foreach) foreachCallstack(elems callstack.Callstack, segments []*BoundSegmentLiteral, e interface{}, useCallValuer bool, valuer MapValuer) (bool, bool) { + for _, frame := range elems { + if f.evalExpr(e, useCallValuer, f.callstackMapValuer(segments, frame), valuer) { + return true, true + } + } + return true, false +} + +func (f *Foreach) callstackMapValuer(segments []*BoundSegmentLiteral, frame callstack.Frame) MapValuer { + var valuer = MapValuer{} + for _, seg := range segments { + key := seg.Value + switch seg.Segment { + case fields.AddressSegment: + valuer[key] = fmt.Sprintf("0x%x", frame.Addr) + case fields.ModuleSegment: + valuer[key] = frame.Module + case fields.SymbolSegment: + valuer[key] = frame.Module + "!" + frame.Symbol + } + } + return valuer +} diff --git a/pkg/filter/ql/function_callstack_windows.go b/pkg/filter/ql/function_callstack_windows.go new file mode 100644 index 000000000..87d8e9bfc --- /dev/null +++ b/pkg/filter/ql/function_callstack_windows.go @@ -0,0 +1,117 @@ +//go:build windows + +/* + * Copyright 2020-2021 by Nedim Sabic Sabic + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ql + +import ( + "github.com/rabbitstack/fibratus/pkg/callstack" + "github.com/rabbitstack/fibratus/pkg/filter/fields" + "github.com/rabbitstack/fibratus/pkg/util/signature" + "golang.org/x/sys/windows" +) + +// foreachCallstack evaluates the predicate against callstack frames. +// The first return value indicates whether callstack handling applied; +// the second is the match result. +func (f *Foreach) foreachCallstack(elems callstack.Callstack, segments []*BoundSegmentLiteral, e interface{}, useCallValuer bool, valuer MapValuer) (bool, bool) { + var pid uint32 + var proc windows.Handle + var err error + + if !elems.IsEmpty() { + pid = elems.FrameAt(0).PID + } + + var desiredAccess uint32 +loop: + for _, seg := range segments { + switch seg.Segment { + case fields.CallsiteLeadingAssemblySegment, fields.CallsiteTrailingAssemblySegment: + desiredAccess = windows.PROCESS_QUERY_INFORMATION | windows.PROCESS_VM_READ + break loop + case fields.AllocationSizeSegment, fields.ProtectionSegment: + desiredAccess = windows.PROCESS_QUERY_INFORMATION + } + } + if desiredAccess != 0 { + proc, err = windows.OpenProcess(desiredAccess, false, pid) + if err != nil { + return true, false + } + defer windows.Close(proc) + } + + for _, frame := range elems { + if f.evalExpr(e, useCallValuer, f.callstackMapValuer(segments, frame, proc), valuer) { + return true, true + } + } + return true, false +} + +func (f *Foreach) callstackMapValuer(segments []*BoundSegmentLiteral, frame callstack.Frame, proc windows.Handle) MapValuer { + var valuer = MapValuer{} + for _, seg := range segments { + key := seg.Value + switch seg.Segment { + case fields.AddressSegment: + valuer[key] = frame.Addr.String() + case fields.OffsetSegment: + valuer[key] = frame.Offset + case fields.IsUnbackedSegment: + valuer[key] = frame.IsUnbacked() + case fields.ModuleSegment: + valuer[key] = frame.Module + case fields.SymbolSegment: + valuer[key] = frame.Module + "!" + frame.Symbol + case fields.AllocationSizeSegment: + valuer[key] = frame.AllocationSize(proc) + case fields.ProtectionSegment: + valuer[key] = frame.Protection(proc) + case fields.CallsiteTrailingAssemblySegment: + valuer[key] = frame.CallsiteAssembly(proc, false) + case fields.CallsiteLeadingAssemblySegment: + valuer[key] = frame.CallsiteAssembly(proc, true) + case fields.ModuleSignatureExistsSegment, fields.ModuleSignatureTrustedSegment, + fields.ModuleSignatureIssuerSegment, fields.ModuleSignatureSubjectSegment: + + sign := signature.GetSignatures().DoRequest(signature.MakeKey(frame.Module, 0, 0, 0)) + if sign == nil { + continue + } + + switch seg.Segment { + case fields.ModuleSignatureExistsSegment: + valuer[key] = sign.Exists() + case fields.ModuleSignatureTrustedSegment: + valuer[key] = sign.IsTrusted() + case fields.ModuleSignatureIssuerSegment: + if sign.HasCertificate() { + valuer[key] = sign.Cert().Issuer + } + case fields.ModuleSignatureSubjectSegment: + if sign.HasCertificate() { + valuer[key] = sign.Cert().Subject + } + } + } + } + return valuer +} diff --git a/pkg/filter/ql/functions/minidump_linux.go b/pkg/filter/ql/functions/minidump_linux.go new file mode 100644 index 000000000..1250a34b0 --- /dev/null +++ b/pkg/filter/ql/functions/minidump_linux.go @@ -0,0 +1,39 @@ +//go:build linux + +/* + * Copyright 2026 by Nedim Sabic Sabic + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package functions + +// IsMinidump determines if the specified file contains the minidump signature. +type IsMinidump struct{} + +func (f IsMinidump) Call(args []interface{}) (interface{}, bool) { + return false, len(args) >= 1 +} + +func (f IsMinidump) Desc() FunctionDesc { + return FunctionDesc{ + Name: IsMinidumpFn, + Args: []FunctionArgDesc{ + {Keyword: "file", Types: []ArgType{Field, BoundField, BoundSegment, BareBoundVariable, Func, String}, Required: true}, + }, + } +} + +func (f IsMinidump) Name() Fn { return IsMinidumpFn } diff --git a/pkg/rules/action/isolate_linux.go b/pkg/rules/action/isolate_linux.go new file mode 100644 index 000000000..fc2584ce4 --- /dev/null +++ b/pkg/rules/action/isolate_linux.go @@ -0,0 +1,32 @@ +//go:build linux + +/* + * Copyright 2026 by Nedim Sabic Sabic + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package action + +import ( + "fmt" + "net" +) + +// Isolate isolates the host via firewall rules. +// Linux isolation is not wired yet. +func Isolate(whitelist []net.IP) error { + return fmt.Errorf("isolate action is not implemented on Linux yet (whitelist=%v)", whitelist) +} diff --git a/pkg/rules/action/kill_linux.go b/pkg/rules/action/kill_linux.go new file mode 100644 index 000000000..077950fa0 --- /dev/null +++ b/pkg/rules/action/kill_linux.go @@ -0,0 +1,29 @@ +//go:build linux + +/* + * Copyright 2026 by Nedim Sabic Sabic + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package action + +import "fmt" + +// Kill terminates all processes with specified pids. +// The signal-based Linux implementation lands with the detection work. +func Kill(pids []uint32) error { + return fmt.Errorf("kill action is not implemented on Linux yet (pids=%v)", pids) +} diff --git a/pkg/rules/compiler.go b/pkg/rules/compiler.go index d0c107df3..f7945b0ec 100644 --- a/pkg/rules/compiler.go +++ b/pkg/rules/compiler.go @@ -58,12 +58,12 @@ var ( ) type compiler struct { - psnap ps.Snapshotter + psnap ps.Resolver config *config.Config approvers config.Approvers } -func newCompiler(psnap ps.Snapshotter, cfg *config.Config) *compiler { +func newCompiler(psnap ps.Resolver, cfg *config.Config) *compiler { return &compiler{psnap: psnap, config: cfg, approvers: config.Approvers{ Keys: make(map[string][]string), Paths: make(map[string][]string), diff --git a/pkg/rules/engine.go b/pkg/rules/engine.go index cd0f4974a..a6cce31df 100644 --- a/pkg/rules/engine.go +++ b/pkg/rules/engine.go @@ -55,7 +55,7 @@ var ( type Engine struct { filters *filterset config *config.Config - psnap ps.Snapshotter + psnap ps.Resolver matches []*ruleMatch mmu sync.Mutex // guards the rule matches slice @@ -130,7 +130,7 @@ func (f *compiledFilter) eval(e *event.Event, valuer *filter.ValuerCache) bool { } // NewEngine builds a fresh rules engine instance. -func NewEngine(psnap ps.Snapshotter, config *config.Config) *Engine { +func NewEngine(psnap ps.Resolver, config *config.Config) *Engine { e := &Engine{ filters: newFilterset(), matches: make([]*ruleMatch, 0), diff --git a/pkg/rules/engine_linux_test.go b/pkg/rules/engine_linux_test.go new file mode 100644 index 000000000..88825e13e --- /dev/null +++ b/pkg/rules/engine_linux_test.go @@ -0,0 +1,36 @@ +//go:build linux + +/* + * Copyright 2026 by Nedim Sabic Sabic + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package rules + +import ( + "testing" + + "github.com/rabbitstack/fibratus/pkg/config" + "github.com/rabbitstack/fibratus/pkg/ps" + "github.com/stretchr/testify/require" +) + +func TestNewEngineAcceptsResolver(t *testing.T) { + cfg := &config.Config{Filters: &config.Filters{}} + e := NewEngine(ps.NewLinuxSnapshotter(), cfg) + require.NotNil(t, e) + require.NotNil(t, e.compiler) +} diff --git a/pkg/rules/sequence.go b/pkg/rules/sequence.go index dfc3d05f7..9015c8eaa 100644 --- a/pkg/rules/sequence.go +++ b/pkg/rules/sequence.go @@ -120,10 +120,10 @@ type sequenceState struct { // The purpose is to enforce temporal monotonicity lastMatch time.Time - psnap ps.Snapshotter + psnap ps.Resolver } -func newSequenceState(f filter.Filter, c *config.FilterConfig, psnap ps.Snapshotter) *sequenceState { +func newSequenceState(f filter.Filter, c *config.FilterConfig, psnap ps.Resolver) *sequenceState { ss := &sequenceState{ filter: f, seq: f.GetSequence(), From ab8c28f3292dea01274e033e714d3d6a424ae63f Mon Sep 17 00:00:00 2001 From: Mostafa Moradian Date: Sat, 8 Aug 2026 21:09:30 +0200 Subject: [PATCH 17/28] chore(build): Attribute new Linux files to Mostafa Moradian Credit newly authored Linux and platform-split files correctly. Keep Nedim's copyright on adapted splits and add a second line for the Linux port work. --- cmd/fibratus/app/config/config_linux.go | 2 +- cmd/fibratus/app/list/list_linux.go | 2 +- cmd/fibratus/app/root_linux.go | 1 + cmd/fibratus/app/root_windows.go | 1 + cmd/fibratus/app/rules/rules_linux.go | 2 +- cmd/fibratus/app/run_linux.go | 1 + cmd/fibratus/app/stats/stats_linux.go | 2 +- cmd/fibratus/main_linux.go | 1 + internal/bootstrap/bootstrap_linux.go | 1 + internal/bootstrap/source_linux.go | 1 + pkg/aggregator/imports_windows.go | 1 + pkg/callstack/callstack_linux.go | 2 +- pkg/cap/version/version_linux.go | 1 + pkg/config/config_linux.go | 2 +- pkg/config/eventsource_linux.go | 2 +- pkg/config/schema_linux.go | 2 +- pkg/event/enum_linux.go | 2 +- pkg/event/event_linux.go | 2 +- pkg/event/event_linux_test.go | 2 +- pkg/event/flags_linux.go | 2 +- pkg/event/formatter_linux.go | 2 +- pkg/event/marshaller_linux.go | 2 +- pkg/event/metainfo_linux.go | 2 +- pkg/event/param_capture_linux.go | 2 +- pkg/event/param_capture_windows.go | 1 + pkg/event/param_linux.go | 2 +- pkg/event/stackwalk_linux.go | 2 +- pkg/event/types_linux.go | 2 +- pkg/filter/accessor_linux.go | 2 +- pkg/filter/accessor_narrow_linux.go | 2 +- pkg/filter/accessor_narrow_windows.go | 1 + pkg/filter/accessor_stubs_linux.go | 2 +- pkg/filter/filter_linux.go | 2 +- pkg/filter/ql/function_callstack_linux.go | 2 +- pkg/filter/ql/function_callstack_windows.go | 1 + pkg/filter/ql/functions/get_reg_value_linux.go | 2 +- pkg/filter/ql/functions/minidump_linux.go | 2 +- pkg/pe/types_linux.go | 2 +- pkg/ps/process_key.go | 2 +- pkg/ps/resolver.go | 2 +- pkg/ps/snapshotter_linux.go | 2 +- pkg/ps/snapshotter_linux_test.go | 2 +- pkg/ps/types/types_linux.go | 2 +- pkg/rules/action/isolate_linux.go | 2 +- pkg/rules/action/kill_linux.go | 2 +- pkg/rules/engine_linux_test.go | 2 +- pkg/util/colorizer/colorizer_stub.go | 2 +- pkg/util/colorizer/colorizer_windows.go | 1 + pkg/util/key/key_linux.go | 2 +- pkg/util/log/logger_linux.go | 2 +- pkg/util/ntstatus/status_linux.go | 2 +- 51 files changed, 51 insertions(+), 39 deletions(-) diff --git a/cmd/fibratus/app/config/config_linux.go b/cmd/fibratus/app/config/config_linux.go index 01ea46121..2bd060ba1 100644 --- a/cmd/fibratus/app/config/config_linux.go +++ b/cmd/fibratus/app/config/config_linux.go @@ -1,7 +1,7 @@ //go:build linux /* - * Copyright 2026 by Nedim Sabic Sabic + * Copyright 2026 by Mostafa Moradian * https://www.fibratus.io * All Rights Reserved. * diff --git a/cmd/fibratus/app/list/list_linux.go b/cmd/fibratus/app/list/list_linux.go index c2c68dcfc..47e64a692 100644 --- a/cmd/fibratus/app/list/list_linux.go +++ b/cmd/fibratus/app/list/list_linux.go @@ -1,7 +1,7 @@ //go:build linux /* - * Copyright 2026 by Nedim Sabic Sabic + * Copyright 2026 by Mostafa Moradian * https://www.fibratus.io * All Rights Reserved. * diff --git a/cmd/fibratus/app/root_linux.go b/cmd/fibratus/app/root_linux.go index 47f828cd6..4250ccca6 100644 --- a/cmd/fibratus/app/root_linux.go +++ b/cmd/fibratus/app/root_linux.go @@ -2,6 +2,7 @@ /* * Copyright 2019-2020 by Nedim Sabic Sabic + * Copyright 2026 by Mostafa Moradian * https://www.fibratus.io * All Rights Reserved. * diff --git a/cmd/fibratus/app/root_windows.go b/cmd/fibratus/app/root_windows.go index f5003f624..8c698a0b0 100644 --- a/cmd/fibratus/app/root_windows.go +++ b/cmd/fibratus/app/root_windows.go @@ -2,6 +2,7 @@ /* * Copyright 2019-2020 by Nedim Sabic Sabic + * Copyright 2026 by Mostafa Moradian * https://www.fibratus.io * All Rights Reserved. * diff --git a/cmd/fibratus/app/rules/rules_linux.go b/cmd/fibratus/app/rules/rules_linux.go index 42ed7d2aa..40250ee20 100644 --- a/cmd/fibratus/app/rules/rules_linux.go +++ b/cmd/fibratus/app/rules/rules_linux.go @@ -1,7 +1,7 @@ //go:build linux /* - * Copyright 2026 by Nedim Sabic Sabic + * Copyright 2026 by Mostafa Moradian * https://www.fibratus.io * All Rights Reserved. * diff --git a/cmd/fibratus/app/run_linux.go b/cmd/fibratus/app/run_linux.go index 58bb7d4bc..3de0b072a 100644 --- a/cmd/fibratus/app/run_linux.go +++ b/cmd/fibratus/app/run_linux.go @@ -2,6 +2,7 @@ /* * Copyright 2019-2020 by Nedim Sabic Sabic + * Copyright 2026 by Mostafa Moradian * https://www.fibratus.io * All Rights Reserved. * diff --git a/cmd/fibratus/app/stats/stats_linux.go b/cmd/fibratus/app/stats/stats_linux.go index 3a5825847..bb4186693 100644 --- a/cmd/fibratus/app/stats/stats_linux.go +++ b/cmd/fibratus/app/stats/stats_linux.go @@ -1,7 +1,7 @@ //go:build linux /* - * Copyright 2026 by Nedim Sabic Sabic + * Copyright 2026 by Mostafa Moradian * https://www.fibratus.io * All Rights Reserved. * diff --git a/cmd/fibratus/main_linux.go b/cmd/fibratus/main_linux.go index 86ff331a3..349a9c889 100644 --- a/cmd/fibratus/main_linux.go +++ b/cmd/fibratus/main_linux.go @@ -1,5 +1,6 @@ /* * Copyright 2019-2020 by Nedim Sabic Sabic + * Copyright 2026 by Mostafa Moradian * https://www.fibratus.io * All Rights Reserved. * diff --git a/internal/bootstrap/bootstrap_linux.go b/internal/bootstrap/bootstrap_linux.go index d07148135..d9d3abc45 100644 --- a/internal/bootstrap/bootstrap_linux.go +++ b/internal/bootstrap/bootstrap_linux.go @@ -2,6 +2,7 @@ /* * Copyright 2021-2022 by Nedim Sabic Sabic + * Copyright 2026 by Mostafa Moradian * https://www.fibratus.io * All Rights Reserved. * diff --git a/internal/bootstrap/source_linux.go b/internal/bootstrap/source_linux.go index 9c6984c83..b4df2a74e 100644 --- a/internal/bootstrap/source_linux.go +++ b/internal/bootstrap/source_linux.go @@ -2,6 +2,7 @@ /* * Copyright 2021-2022 by Nedim Sabic Sabic + * Copyright 2026 by Mostafa Moradian * https://www.fibratus.io * All Rights Reserved. * diff --git a/pkg/aggregator/imports_windows.go b/pkg/aggregator/imports_windows.go index e65eed8a7..2e18307a0 100644 --- a/pkg/aggregator/imports_windows.go +++ b/pkg/aggregator/imports_windows.go @@ -2,6 +2,7 @@ /* * Copyright 2019-2020 by Nedim Sabic Sabic + * Copyright 2026 by Mostafa Moradian * https://www.fibratus.io * All Rights Reserved. * diff --git a/pkg/callstack/callstack_linux.go b/pkg/callstack/callstack_linux.go index 268634821..711cfb678 100644 --- a/pkg/callstack/callstack_linux.go +++ b/pkg/callstack/callstack_linux.go @@ -1,7 +1,7 @@ //go:build linux /* - * Copyright 2026 by Nedim Sabic Sabic + * Copyright 2026 by Mostafa Moradian * https://www.fibratus.io * All Rights Reserved. * diff --git a/pkg/cap/version/version_linux.go b/pkg/cap/version/version_linux.go index df2a03809..1e1e1aef3 100644 --- a/pkg/cap/version/version_linux.go +++ b/pkg/cap/version/version_linux.go @@ -2,6 +2,7 @@ /* * Copyright 2019-2020 by Nedim Sabic Sabic + * Copyright 2026 by Mostafa Moradian * https://www.fibratus.io * All Rights Reserved. * diff --git a/pkg/config/config_linux.go b/pkg/config/config_linux.go index ecd0fd8c8..c0295c0a0 100644 --- a/pkg/config/config_linux.go +++ b/pkg/config/config_linux.go @@ -1,7 +1,7 @@ //go:build linux /* - * Copyright 2026 by Nedim Sabic Sabic + * Copyright 2026 by Mostafa Moradian * https://www.fibratus.io * All Rights Reserved. * diff --git a/pkg/config/eventsource_linux.go b/pkg/config/eventsource_linux.go index 43e7476bd..68b2f12a7 100644 --- a/pkg/config/eventsource_linux.go +++ b/pkg/config/eventsource_linux.go @@ -1,7 +1,7 @@ //go:build linux /* - * Copyright 2026 by Nedim Sabic Sabic + * Copyright 2026 by Mostafa Moradian * https://www.fibratus.io * All Rights Reserved. * diff --git a/pkg/config/schema_linux.go b/pkg/config/schema_linux.go index 6329e0a8b..136a9a4ae 100644 --- a/pkg/config/schema_linux.go +++ b/pkg/config/schema_linux.go @@ -1,7 +1,7 @@ //go:build linux /* - * Copyright 2026 by Nedim Sabic Sabic + * Copyright 2026 by Mostafa Moradian * https://www.fibratus.io * All Rights Reserved. * diff --git a/pkg/event/enum_linux.go b/pkg/event/enum_linux.go index ac2900f5c..7ed359caa 100644 --- a/pkg/event/enum_linux.go +++ b/pkg/event/enum_linux.go @@ -1,7 +1,7 @@ //go:build linux /* - * Copyright 2026 by Nedim Sabic Sabic + * Copyright 2026 by Mostafa Moradian * https://www.fibratus.io * All Rights Reserved. * diff --git a/pkg/event/event_linux.go b/pkg/event/event_linux.go index ff1ecad48..493ae4616 100644 --- a/pkg/event/event_linux.go +++ b/pkg/event/event_linux.go @@ -1,7 +1,7 @@ //go:build linux /* - * Copyright 2026 by Nedim Sabic Sabic + * Copyright 2026 by Mostafa Moradian * https://www.fibratus.io * All Rights Reserved. * diff --git a/pkg/event/event_linux_test.go b/pkg/event/event_linux_test.go index 4365e32c6..79a6ad5e3 100644 --- a/pkg/event/event_linux_test.go +++ b/pkg/event/event_linux_test.go @@ -1,7 +1,7 @@ //go:build linux /* - * Copyright 2026 by Nedim Sabic Sabic + * Copyright 2026 by Mostafa Moradian * https://www.fibratus.io * All Rights Reserved. * diff --git a/pkg/event/flags_linux.go b/pkg/event/flags_linux.go index e035ff98d..f7d187755 100644 --- a/pkg/event/flags_linux.go +++ b/pkg/event/flags_linux.go @@ -1,7 +1,7 @@ //go:build linux /* - * Copyright 2026 by Nedim Sabic Sabic + * Copyright 2026 by Mostafa Moradian * https://www.fibratus.io * All Rights Reserved. * diff --git a/pkg/event/formatter_linux.go b/pkg/event/formatter_linux.go index 720e3cf43..8e3322ac5 100644 --- a/pkg/event/formatter_linux.go +++ b/pkg/event/formatter_linux.go @@ -1,7 +1,7 @@ //go:build linux /* - * Copyright 2026 by Nedim Sabic Sabic + * Copyright 2026 by Mostafa Moradian * https://www.fibratus.io * All Rights Reserved. * diff --git a/pkg/event/marshaller_linux.go b/pkg/event/marshaller_linux.go index b187ec12e..0a3be0a01 100644 --- a/pkg/event/marshaller_linux.go +++ b/pkg/event/marshaller_linux.go @@ -1,7 +1,7 @@ //go:build linux /* - * Copyright 2026 by Nedim Sabic Sabic + * Copyright 2026 by Mostafa Moradian * https://www.fibratus.io * All Rights Reserved. * diff --git a/pkg/event/metainfo_linux.go b/pkg/event/metainfo_linux.go index 2a607787a..4378f1a8a 100644 --- a/pkg/event/metainfo_linux.go +++ b/pkg/event/metainfo_linux.go @@ -1,7 +1,7 @@ //go:build linux /* - * Copyright 2026 by Nedim Sabic Sabic + * Copyright 2026 by Mostafa Moradian * https://www.fibratus.io * All Rights Reserved. * diff --git a/pkg/event/param_capture_linux.go b/pkg/event/param_capture_linux.go index b55f892e9..c1b2c661a 100644 --- a/pkg/event/param_capture_linux.go +++ b/pkg/event/param_capture_linux.go @@ -1,7 +1,7 @@ //go:build linux /* - * Copyright 2026 by Nedim Sabic Sabic + * Copyright 2026 by Mostafa Moradian * https://www.fibratus.io * All Rights Reserved. * diff --git a/pkg/event/param_capture_windows.go b/pkg/event/param_capture_windows.go index e64a44002..d8c79be40 100644 --- a/pkg/event/param_capture_windows.go +++ b/pkg/event/param_capture_windows.go @@ -2,6 +2,7 @@ /* * Copyright 2019-2020 by Nedim Sabic Sabic + * Copyright 2026 by Mostafa Moradian * https://www.fibratus.io * All Rights Reserved. * diff --git a/pkg/event/param_linux.go b/pkg/event/param_linux.go index 9c80d5a05..af0a2ce89 100644 --- a/pkg/event/param_linux.go +++ b/pkg/event/param_linux.go @@ -1,7 +1,7 @@ //go:build linux /* - * Copyright 2026 by Nedim Sabic Sabic + * Copyright 2026 by Mostafa Moradian * https://www.fibratus.io * All Rights Reserved. * diff --git a/pkg/event/stackwalk_linux.go b/pkg/event/stackwalk_linux.go index 0f92b68fe..7d3684f51 100644 --- a/pkg/event/stackwalk_linux.go +++ b/pkg/event/stackwalk_linux.go @@ -1,7 +1,7 @@ //go:build linux /* - * Copyright 2026 by Nedim Sabic Sabic + * Copyright 2026 by Mostafa Moradian * https://www.fibratus.io * All Rights Reserved. * diff --git a/pkg/event/types_linux.go b/pkg/event/types_linux.go index 60af41af5..0513861e4 100644 --- a/pkg/event/types_linux.go +++ b/pkg/event/types_linux.go @@ -1,7 +1,7 @@ //go:build linux /* - * Copyright 2026 by Nedim Sabic Sabic + * Copyright 2026 by Mostafa Moradian * https://www.fibratus.io * All Rights Reserved. * diff --git a/pkg/filter/accessor_linux.go b/pkg/filter/accessor_linux.go index b1aac733d..59ceb97b7 100644 --- a/pkg/filter/accessor_linux.go +++ b/pkg/filter/accessor_linux.go @@ -1,7 +1,7 @@ //go:build linux /* - * Copyright 2026 by Nedim Sabic Sabic + * Copyright 2026 by Mostafa Moradian * https://www.fibratus.io * All Rights Reserved. * diff --git a/pkg/filter/accessor_narrow_linux.go b/pkg/filter/accessor_narrow_linux.go index 187a7020e..1e9105ca0 100644 --- a/pkg/filter/accessor_narrow_linux.go +++ b/pkg/filter/accessor_narrow_linux.go @@ -1,7 +1,7 @@ //go:build linux /* - * Copyright 2026 by Nedim Sabic Sabic + * Copyright 2026 by Mostafa Moradian * https://www.fibratus.io * All Rights Reserved. * diff --git a/pkg/filter/accessor_narrow_windows.go b/pkg/filter/accessor_narrow_windows.go index 0d1947f96..239f17323 100644 --- a/pkg/filter/accessor_narrow_windows.go +++ b/pkg/filter/accessor_narrow_windows.go @@ -2,6 +2,7 @@ /* * Copyright 2020-2021 by Nedim Sabic Sabic + * Copyright 2026 by Mostafa Moradian * https://www.fibratus.io * All Rights Reserved. * diff --git a/pkg/filter/accessor_stubs_linux.go b/pkg/filter/accessor_stubs_linux.go index a66afd9b4..e89696f3b 100644 --- a/pkg/filter/accessor_stubs_linux.go +++ b/pkg/filter/accessor_stubs_linux.go @@ -1,7 +1,7 @@ //go:build linux /* - * Copyright 2026 by Nedim Sabic Sabic + * Copyright 2026 by Mostafa Moradian * https://www.fibratus.io * All Rights Reserved. * diff --git a/pkg/filter/filter_linux.go b/pkg/filter/filter_linux.go index 44179cbff..42ad1eb0a 100644 --- a/pkg/filter/filter_linux.go +++ b/pkg/filter/filter_linux.go @@ -1,7 +1,7 @@ //go:build linux /* - * Copyright 2026 by Nedim Sabic Sabic + * Copyright 2026 by Mostafa Moradian * https://www.fibratus.io * All Rights Reserved. * diff --git a/pkg/filter/ql/function_callstack_linux.go b/pkg/filter/ql/function_callstack_linux.go index 1b618439a..3f0754c58 100644 --- a/pkg/filter/ql/function_callstack_linux.go +++ b/pkg/filter/ql/function_callstack_linux.go @@ -1,7 +1,7 @@ //go:build linux /* - * Copyright 2026 by Nedim Sabic Sabic + * Copyright 2026 by Mostafa Moradian * https://www.fibratus.io * All Rights Reserved. * diff --git a/pkg/filter/ql/function_callstack_windows.go b/pkg/filter/ql/function_callstack_windows.go index 87d8e9bfc..d8434036e 100644 --- a/pkg/filter/ql/function_callstack_windows.go +++ b/pkg/filter/ql/function_callstack_windows.go @@ -2,6 +2,7 @@ /* * Copyright 2020-2021 by Nedim Sabic Sabic + * Copyright 2026 by Mostafa Moradian * https://www.fibratus.io * All Rights Reserved. * diff --git a/pkg/filter/ql/functions/get_reg_value_linux.go b/pkg/filter/ql/functions/get_reg_value_linux.go index 926363826..6295a79cd 100644 --- a/pkg/filter/ql/functions/get_reg_value_linux.go +++ b/pkg/filter/ql/functions/get_reg_value_linux.go @@ -1,7 +1,7 @@ //go:build linux /* - * Copyright 2026 by Nedim Sabic Sabic + * Copyright 2026 by Mostafa Moradian * https://www.fibratus.io * All Rights Reserved. * diff --git a/pkg/filter/ql/functions/minidump_linux.go b/pkg/filter/ql/functions/minidump_linux.go index 1250a34b0..98e57df6b 100644 --- a/pkg/filter/ql/functions/minidump_linux.go +++ b/pkg/filter/ql/functions/minidump_linux.go @@ -1,7 +1,7 @@ //go:build linux /* - * Copyright 2026 by Nedim Sabic Sabic + * Copyright 2026 by Mostafa Moradian * https://www.fibratus.io * All Rights Reserved. * diff --git a/pkg/pe/types_linux.go b/pkg/pe/types_linux.go index 783d077be..767bcaa34 100644 --- a/pkg/pe/types_linux.go +++ b/pkg/pe/types_linux.go @@ -1,7 +1,7 @@ //go:build linux /* - * Copyright 2026 by Nedim Sabic Sabic + * Copyright 2026 by Mostafa Moradian * https://www.fibratus.io * All Rights Reserved. * diff --git a/pkg/ps/process_key.go b/pkg/ps/process_key.go index 0834f50aa..250edf1b0 100644 --- a/pkg/ps/process_key.go +++ b/pkg/ps/process_key.go @@ -1,5 +1,5 @@ /* - * Copyright 2026 by Nedim Sabic Sabic + * Copyright 2026 by Mostafa Moradian * https://www.fibratus.io * All Rights Reserved. * diff --git a/pkg/ps/resolver.go b/pkg/ps/resolver.go index 67414c3d8..4f3e07d9b 100644 --- a/pkg/ps/resolver.go +++ b/pkg/ps/resolver.go @@ -1,5 +1,5 @@ /* - * Copyright 2026 by Nedim Sabic Sabic + * Copyright 2026 by Mostafa Moradian * https://www.fibratus.io * All Rights Reserved. * diff --git a/pkg/ps/snapshotter_linux.go b/pkg/ps/snapshotter_linux.go index 10ca04fe4..0b4f9d9cf 100644 --- a/pkg/ps/snapshotter_linux.go +++ b/pkg/ps/snapshotter_linux.go @@ -1,7 +1,7 @@ //go:build linux /* - * Copyright 2026 by Nedim Sabic Sabic + * Copyright 2026 by Mostafa Moradian * https://www.fibratus.io * All Rights Reserved. * diff --git a/pkg/ps/snapshotter_linux_test.go b/pkg/ps/snapshotter_linux_test.go index 6638ed6a7..1c6b178b1 100644 --- a/pkg/ps/snapshotter_linux_test.go +++ b/pkg/ps/snapshotter_linux_test.go @@ -1,7 +1,7 @@ //go:build linux /* - * Copyright 2026 by Nedim Sabic Sabic + * Copyright 2026 by Mostafa Moradian * https://www.fibratus.io * All Rights Reserved. * diff --git a/pkg/ps/types/types_linux.go b/pkg/ps/types/types_linux.go index 8c6ffc906..d52196646 100644 --- a/pkg/ps/types/types_linux.go +++ b/pkg/ps/types/types_linux.go @@ -1,7 +1,7 @@ //go:build linux /* - * Copyright 2026 by Nedim Sabic Sabic + * Copyright 2026 by Mostafa Moradian * https://www.fibratus.io * All Rights Reserved. * diff --git a/pkg/rules/action/isolate_linux.go b/pkg/rules/action/isolate_linux.go index fc2584ce4..3684e56bb 100644 --- a/pkg/rules/action/isolate_linux.go +++ b/pkg/rules/action/isolate_linux.go @@ -1,7 +1,7 @@ //go:build linux /* - * Copyright 2026 by Nedim Sabic Sabic + * Copyright 2026 by Mostafa Moradian * https://www.fibratus.io * All Rights Reserved. * diff --git a/pkg/rules/action/kill_linux.go b/pkg/rules/action/kill_linux.go index 077950fa0..04ff289f8 100644 --- a/pkg/rules/action/kill_linux.go +++ b/pkg/rules/action/kill_linux.go @@ -1,7 +1,7 @@ //go:build linux /* - * Copyright 2026 by Nedim Sabic Sabic + * Copyright 2026 by Mostafa Moradian * https://www.fibratus.io * All Rights Reserved. * diff --git a/pkg/rules/engine_linux_test.go b/pkg/rules/engine_linux_test.go index 88825e13e..59c26b68d 100644 --- a/pkg/rules/engine_linux_test.go +++ b/pkg/rules/engine_linux_test.go @@ -1,7 +1,7 @@ //go:build linux /* - * Copyright 2026 by Nedim Sabic Sabic + * Copyright 2026 by Mostafa Moradian * https://www.fibratus.io * All Rights Reserved. * diff --git a/pkg/util/colorizer/colorizer_stub.go b/pkg/util/colorizer/colorizer_stub.go index 81c41e660..dbf2e6a41 100644 --- a/pkg/util/colorizer/colorizer_stub.go +++ b/pkg/util/colorizer/colorizer_stub.go @@ -1,7 +1,7 @@ //go:build !windows /* - * Copyright 2026 by Nedim Sabic Sabic + * Copyright 2026 by Mostafa Moradian * https://www.fibratus.io * All Rights Reserved. * diff --git a/pkg/util/colorizer/colorizer_windows.go b/pkg/util/colorizer/colorizer_windows.go index 7018ef0fc..4341075e2 100644 --- a/pkg/util/colorizer/colorizer_windows.go +++ b/pkg/util/colorizer/colorizer_windows.go @@ -2,6 +2,7 @@ /* * Copyright 2021-present by Nedim Sabic Sabic + * Copyright 2026 by Mostafa Moradian * https://www.fibratus.io * All Rights Reserved. * diff --git a/pkg/util/key/key_linux.go b/pkg/util/key/key_linux.go index 891a85fb1..ba9fb74ab 100644 --- a/pkg/util/key/key_linux.go +++ b/pkg/util/key/key_linux.go @@ -1,7 +1,7 @@ //go:build linux /* - * Copyright 2026 by Nedim Sabic Sabic + * Copyright 2026 by Mostafa Moradian * https://www.fibratus.io * All Rights Reserved. * diff --git a/pkg/util/log/logger_linux.go b/pkg/util/log/logger_linux.go index cd20c902c..7f90ed330 100644 --- a/pkg/util/log/logger_linux.go +++ b/pkg/util/log/logger_linux.go @@ -1,7 +1,7 @@ //go:build linux /* - * Copyright 2026 by Nedim Sabic Sabic + * Copyright 2026 by Mostafa Moradian * https://www.fibratus.io * All Rights Reserved. * diff --git a/pkg/util/ntstatus/status_linux.go b/pkg/util/ntstatus/status_linux.go index 5c0e02286..59b931d0e 100644 --- a/pkg/util/ntstatus/status_linux.go +++ b/pkg/util/ntstatus/status_linux.go @@ -1,7 +1,7 @@ //go:build linux /* - * Copyright 2026 by Nedim Sabic Sabic + * Copyright 2026 by Mostafa Moradian * https://www.fibratus.io * All Rights Reserved. * From 4e66392fb947863cbd11c11b4c18f0313417d0f2 Mon Sep 17 00:00:00 2001 From: Mostafa Moradian Date: Sun, 9 Aug 2026 10:34:53 +0200 Subject: [PATCH 18/28] chore(ebpf): Attribute eBPF spike files to Mostafa Moradian Align copyright headers on the Linux eBPF feasibility spike with the rest of the Linux port work. --- internal/ebpf/doc.go | 2 +- internal/ebpf/features.go | 2 +- internal/ebpf/features_test.go | 2 +- internal/ebpf/reconcile.go | 2 +- internal/ebpf/reconcile_test.go | 2 +- internal/ebpf/spike/cmd/spike/main.go | 2 +- internal/ebpf/spike/enrich.go | 2 +- internal/ebpf/spike/event.go | 2 +- internal/ebpf/spike/gen.go | 2 +- internal/ebpf/spike/run.go | 2 +- 10 files changed, 10 insertions(+), 10 deletions(-) diff --git a/internal/ebpf/doc.go b/internal/ebpf/doc.go index 6b50b1917..ca37ad037 100644 --- a/internal/ebpf/doc.go +++ b/internal/ebpf/doc.go @@ -1,5 +1,5 @@ /* - * Copyright 2026 Fibratus contributors + * Copyright 2026 by Mostafa Moradian * https://www.fibratus.io * All Rights Reserved. * diff --git a/internal/ebpf/features.go b/internal/ebpf/features.go index ea9ecf695..d350449f2 100644 --- a/internal/ebpf/features.go +++ b/internal/ebpf/features.go @@ -1,7 +1,7 @@ //go:build linux /* - * Copyright 2026 Fibratus contributors + * Copyright 2026 by Mostafa Moradian * https://www.fibratus.io * All Rights Reserved. * diff --git a/internal/ebpf/features_test.go b/internal/ebpf/features_test.go index 430767e2d..0ea741b66 100644 --- a/internal/ebpf/features_test.go +++ b/internal/ebpf/features_test.go @@ -1,7 +1,7 @@ //go:build linux /* - * Copyright 2026 Fibratus contributors + * Copyright 2026 by Mostafa Moradian * https://www.fibratus.io * All Rights Reserved. * diff --git a/internal/ebpf/reconcile.go b/internal/ebpf/reconcile.go index 2d939c981..072ae26e5 100644 --- a/internal/ebpf/reconcile.go +++ b/internal/ebpf/reconcile.go @@ -1,5 +1,5 @@ /* - * Copyright 2026 Fibratus contributors + * Copyright 2026 by Mostafa Moradian * https://www.fibratus.io * All Rights Reserved. * diff --git a/internal/ebpf/reconcile_test.go b/internal/ebpf/reconcile_test.go index 516bf078e..cc20817b4 100644 --- a/internal/ebpf/reconcile_test.go +++ b/internal/ebpf/reconcile_test.go @@ -1,5 +1,5 @@ /* - * Copyright 2026 Fibratus contributors + * Copyright 2026 by Mostafa Moradian * https://www.fibratus.io * All Rights Reserved. * diff --git a/internal/ebpf/spike/cmd/spike/main.go b/internal/ebpf/spike/cmd/spike/main.go index 27d16c474..46efe842d 100644 --- a/internal/ebpf/spike/cmd/spike/main.go +++ b/internal/ebpf/spike/cmd/spike/main.go @@ -1,7 +1,7 @@ //go:build linux /* - * Copyright 2026 Fibratus contributors + * Copyright 2026 by Mostafa Moradian * https://www.fibratus.io * All Rights Reserved. * diff --git a/internal/ebpf/spike/enrich.go b/internal/ebpf/spike/enrich.go index fa57410a3..9376b8bcf 100644 --- a/internal/ebpf/spike/enrich.go +++ b/internal/ebpf/spike/enrich.go @@ -1,7 +1,7 @@ //go:build linux /* - * Copyright 2026 Fibratus contributors + * Copyright 2026 by Mostafa Moradian * https://www.fibratus.io * All Rights Reserved. * diff --git a/internal/ebpf/spike/event.go b/internal/ebpf/spike/event.go index d4211d07d..f86f5dfac 100644 --- a/internal/ebpf/spike/event.go +++ b/internal/ebpf/spike/event.go @@ -1,7 +1,7 @@ //go:build linux /* - * Copyright 2026 Fibratus contributors + * Copyright 2026 by Mostafa Moradian * https://www.fibratus.io * All Rights Reserved. * diff --git a/internal/ebpf/spike/gen.go b/internal/ebpf/spike/gen.go index 5db6245d9..1e9349f1c 100644 --- a/internal/ebpf/spike/gen.go +++ b/internal/ebpf/spike/gen.go @@ -1,7 +1,7 @@ //go:build linux /* - * Copyright 2026 Fibratus contributors + * Copyright 2026 by Mostafa Moradian * https://www.fibratus.io * All Rights Reserved. * diff --git a/internal/ebpf/spike/run.go b/internal/ebpf/spike/run.go index 4c223b925..c313bf0ae 100644 --- a/internal/ebpf/spike/run.go +++ b/internal/ebpf/spike/run.go @@ -1,7 +1,7 @@ //go:build linux /* - * Copyright 2026 Fibratus contributors + * Copyright 2026 by Mostafa Moradian * https://www.fibratus.io * All Rights Reserved. * From bff3335dbc228962a2019a8552554c3602cbf912 Mon Sep 17 00:00:00 2001 From: Mostafa Moradian Date: Mon, 10 Aug 2026 16:30:54 +0200 Subject: [PATCH 19/28] refactor(cli): Share config/list/rules/stats commands across platforms Restore the platform-agnostic CLI entrypoints and keep only the Stats struct Linux/Windows specific. Add Linux DialPipe and hostname helpers so the shared commands compile. --- cmd/fibratus/app/config/config.go | 2 - cmd/fibratus/app/list/list.go | 2 - cmd/fibratus/app/list/list_linux.go | 25 ----- cmd/fibratus/app/rules/create.go | 2 - cmd/fibratus/app/rules/list.go | 2 - cmd/fibratus/app/rules/rules.go | 2 - cmd/fibratus/app/rules/rules_linux.go | 25 ----- cmd/fibratus/app/rules/validate.go | 2 - cmd/fibratus/app/stats/stats.go | 75 --------------- cmd/fibratus/app/stats/stats_linux.go | 5 +- cmd/fibratus/app/stats/stats_windows.go | 94 +++++++++++++++++++ .../{bootstrap.go => bootstrap_windows.go} | 0 .../{source.go => source_windows.go} | 0 ...ports_windows.go => aggregator_windows.go} | 0 .../api/listener_linux.go | 15 ++- .../{callstack.go => callstack_windows.go} | 0 pkg/util/hostname/hostname_linux.go | 81 ++++++++++++++++ 17 files changed, 189 insertions(+), 143 deletions(-) delete mode 100644 cmd/fibratus/app/list/list_linux.go delete mode 100644 cmd/fibratus/app/rules/rules_linux.go create mode 100644 cmd/fibratus/app/stats/stats_windows.go rename internal/bootstrap/{bootstrap.go => bootstrap_windows.go} (100%) rename internal/bootstrap/{source.go => source_windows.go} (100%) rename pkg/aggregator/{imports_windows.go => aggregator_windows.go} (100%) rename cmd/fibratus/app/config/config_linux.go => pkg/api/listener_linux.go (64%) rename pkg/callstack/{callstack.go => callstack_windows.go} (100%) create mode 100644 pkg/util/hostname/hostname_linux.go diff --git a/cmd/fibratus/app/config/config.go b/cmd/fibratus/app/config/config.go index 62679dd8a..88810d92b 100644 --- a/cmd/fibratus/app/config/config.go +++ b/cmd/fibratus/app/config/config.go @@ -1,5 +1,3 @@ -//go:build windows - /* * Copyright 2019-2020 by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/cmd/fibratus/app/list/list.go b/cmd/fibratus/app/list/list.go index 961e4e107..92ab1eff6 100644 --- a/cmd/fibratus/app/list/list.go +++ b/cmd/fibratus/app/list/list.go @@ -1,5 +1,3 @@ -//go:build windows - /* * Copyright 2019-2020 by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/cmd/fibratus/app/list/list_linux.go b/cmd/fibratus/app/list/list_linux.go deleted file mode 100644 index 47e64a692..000000000 --- a/cmd/fibratus/app/list/list_linux.go +++ /dev/null @@ -1,25 +0,0 @@ -//go:build linux - -/* - * Copyright 2026 by Mostafa Moradian - * https://www.fibratus.io - * All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package list - -import "github.com/spf13/cobra" - -var Command = &cobra.Command{Use: "list", Short: "Show available Linux runtime information"} diff --git a/cmd/fibratus/app/rules/create.go b/cmd/fibratus/app/rules/create.go index 12f55f6cb..c21dc3bbc 100644 --- a/cmd/fibratus/app/rules/create.go +++ b/cmd/fibratus/app/rules/create.go @@ -1,5 +1,3 @@ -//go:build windows - /* * Copyright 2021-2022 by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/cmd/fibratus/app/rules/list.go b/cmd/fibratus/app/rules/list.go index 525dd0217..666af4f6d 100644 --- a/cmd/fibratus/app/rules/list.go +++ b/cmd/fibratus/app/rules/list.go @@ -1,5 +1,3 @@ -//go:build windows - /* * Copyright 2021-2022 by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/cmd/fibratus/app/rules/rules.go b/cmd/fibratus/app/rules/rules.go index ca387bfdb..d925aa557 100644 --- a/cmd/fibratus/app/rules/rules.go +++ b/cmd/fibratus/app/rules/rules.go @@ -1,5 +1,3 @@ -//go:build windows - /* * Copyright 2021-2022 by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/cmd/fibratus/app/rules/rules_linux.go b/cmd/fibratus/app/rules/rules_linux.go deleted file mode 100644 index 40250ee20..000000000 --- a/cmd/fibratus/app/rules/rules_linux.go +++ /dev/null @@ -1,25 +0,0 @@ -//go:build linux - -/* - * Copyright 2026 by Mostafa Moradian - * https://www.fibratus.io - * All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package rules - -import "github.com/spf13/cobra" - -var Command = &cobra.Command{Use: "rules", Short: "Manage detection rules"} diff --git a/cmd/fibratus/app/rules/validate.go b/cmd/fibratus/app/rules/validate.go index 56b2b227f..9ab621d04 100644 --- a/cmd/fibratus/app/rules/validate.go +++ b/cmd/fibratus/app/rules/validate.go @@ -1,5 +1,3 @@ -//go:build windows - /* * Copyright 2021-2022 by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/cmd/fibratus/app/stats/stats.go b/cmd/fibratus/app/stats/stats.go index b8d5c5e25..4c0c113df 100644 --- a/cmd/fibratus/app/stats/stats.go +++ b/cmd/fibratus/app/stats/stats.go @@ -1,5 +1,3 @@ -//go:build windows - /* * Copyright 2019-2020 by Nedim Sabic Sabic * https://www.fibratus.io @@ -45,79 +43,6 @@ func init() { cfg.MustViperize(Command) } -// Stats stores runtime statistics that are retrieved from the expvar endpoint. -type Stats struct { - AggregatorBatchEvents int `json:"aggregator.batch.events"` - AggregatorFlushesCount int `json:"aggregator.flushes.count"` - AggregatorEventErrors int `json:"aggregator.event.errors"` - AggregatorTransformerErrors map[string]int `json:"aggregator.transformer.errors"` - AggregatorWorkerClientPublishErrors int `json:"aggregator.worker.client.publish.errors"` - FilamentDictErrors int `json:"filament.dict.errors"` - FilamentEventBatchFlushes int `json:"filament.event.batch.flushes"` - FilamentEventErrors map[string]int `json:"filament.event.errors"` - FilamentEventProcessErrors int `json:"filament.event.process.errors"` - FilterAccessorErrors map[string]int `json:"filter.accessor.errors"` - FsFileObjectHandleHits int `json:"fs.file.object.handle.hits"` - FsFileObjectMisses int `json:"fs.file.object.misses"` - FsFileReleases int `json:"fs.file.releases"` - FsTotalRundownFiles int `json:"fs.total.rundown.files"` - HandleDeferredEvictions int `json:"handle.deferred.evictions"` - HandleNameQueryFailures map[string]int `json:"handle.name.query.failures"` - HandleSnapshotCount int `json:"handle.snapshot.count"` - HandleSnapshotBytes int `json:"handle.snapshot.bytes"` - HandleTypesCount int `json:"handle.types.count"` - HandleTypeNameMisses int `json:"handle.type.name.misses"` - HandleWaitTimeouts int `json:"handle.wait.timeouts"` - HostnameErrors map[string]int `json:"hostname.errors"` - CapFlusherErrors map[string]int `json:"cap.flusher.errors"` - CapHandleWriteErrors int `json:"cap.handle.write.errors"` - CapEventUnmarshalErrors int `json:"cap.event.unmarshal.errors"` - CapEventWriteErrors int `json:"cap.event.write.errors"` - CapEventSourceConsumerErrors int `json:"cap.eventsource.consumer.errors"` - CapOverflowErrors int `json:"cap.overflow.errors"` - CapReadBytes int `json:"cap.read.bytes"` - CapReadEvents int `json:"cap.read.events"` - CapReaderDroppedByFilter int `json:"cap.reader.dropped.by.filter"` - CapReaderHandleUnmarshalErrors int `json:"cap.reader.handle.unmarshal.errors"` - EventProcessorFailures int `json:"event.processor.failures"` - EventSeqInitErrors map[string]int `json:"event.seq.init.errors"` - EventSeqStoreErrors int `json:"event.seq.store.errors"` - EventTimestampUnmarshalErrors int `json:"event.timestamp.unmarshal.errors"` - EventSourceBuffersRead int `json:"eventsource.buffers.read"` - EventSourceEventsEnqueued int `json:"eventsource.events.enqueued"` - EventSourceEventsDequeued int `json:"eventsource.events.dequeued"` - EventSourceUnknownEvents int `json:"eventsource.events.unknown"` - EventSourceEventsProcessed int `json:"eventsource.events.processed"` - EventSourceExcludedEvents int `json:"eventsource.excluded.events"` - EventSourceEventsFailures map[string]int `json:"eventsource.events.failures"` - LoggerErrors map[string]int `json:"logger.errors"` - OutputAMQPChannelFailures int `json:"output.amqp.channel.failures"` - OutputAMQPConnectionFailures int `json:"output.amqp.connection.failures"` - OutputAMQPPublishErrors int `json:"output.amqp.publish.errors"` - OutputConsoleErrors int `json:"output.console.errors"` - OutputNullBlackholeEvents int `json:"output.null.blackhole.events"` - PeSkippedImages int `json:"pe.skipped.images"` - PeDirectoryParseErrors int `json:"pe.directory.parse.errors"` - PeVersionResourcesParseErrors int `json:"pe.version.resources.parse.errors"` - ProcessCount int `json:"process.count"` - ProcessModuleCount int `json:"process.module.count"` - ProcessLookupFailureCount map[int]int `json:"process.lookup.failure.count"` - ProcessPebReadErrors int `json:"process.peb.read.errors"` - ProcessReaped int `json:"process.reaped"` - ProcessThreadCount int `json:"process.thread.count"` - RegistryKcbCount int `json:"registry.kcb.count"` - RegistryKcbMisses int `json:"registry.kcb.misses"` - RegistryKeyHandleHits int `json:"registry.key.handle.hits"` - RegistryUnknownKeysCount int `json:"registry.unknown.keys.count"` - StackwalkEnqueued int `json:"stackwalk.enqueued"` - StackwalkFlushes int `json:"stackwalk.flushes"` - StackwalkFlushesProcs map[string]int `json:"stackwalk.flushes.procs"` - StackwalkFlushesEvents map[string]int `json:"stackwalk.flushes.events"` - YaraImageScans int `json:"yara.image.scans"` - YaraProcScans int `json:"yara.proc.scans"` - YaraRuleMatches int `json:"yara.rule.matches"` -} - func stats(cmd *cobra.Command, args []string) error { if err := bootstrap.InitConfigAndLogger(cfg); err != nil { return err diff --git a/cmd/fibratus/app/stats/stats_linux.go b/cmd/fibratus/app/stats/stats_linux.go index bb4186693..da5a11dfb 100644 --- a/cmd/fibratus/app/stats/stats_linux.go +++ b/cmd/fibratus/app/stats/stats_linux.go @@ -20,6 +20,5 @@ package stats -import "github.com/spf13/cobra" - -var Command = &cobra.Command{Use: "stats", Short: "Show runtime statistics"} +// Stats stores runtime statistics that are retrieved from the expvar endpoint. +type Stats struct{} diff --git a/cmd/fibratus/app/stats/stats_windows.go b/cmd/fibratus/app/stats/stats_windows.go new file mode 100644 index 000000000..407eec3f3 --- /dev/null +++ b/cmd/fibratus/app/stats/stats_windows.go @@ -0,0 +1,94 @@ +//go:build windows + +/* + * Copyright 2019-2020 by Nedim Sabic Sabic + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package stats + +// Stats stores runtime statistics that are retrieved from the expvar endpoint. +type Stats struct { + AggregatorBatchEvents int `json:"aggregator.batch.events"` + AggregatorFlushesCount int `json:"aggregator.flushes.count"` + AggregatorEventErrors int `json:"aggregator.event.errors"` + AggregatorTransformerErrors map[string]int `json:"aggregator.transformer.errors"` + AggregatorWorkerClientPublishErrors int `json:"aggregator.worker.client.publish.errors"` + FilamentDictErrors int `json:"filament.dict.errors"` + FilamentEventBatchFlushes int `json:"filament.event.batch.flushes"` + FilamentEventErrors map[string]int `json:"filament.event.errors"` + FilamentEventProcessErrors int `json:"filament.event.process.errors"` + FilterAccessorErrors map[string]int `json:"filter.accessor.errors"` + FsFileObjectHandleHits int `json:"fs.file.object.handle.hits"` + FsFileObjectMisses int `json:"fs.file.object.misses"` + FsFileReleases int `json:"fs.file.releases"` + FsTotalRundownFiles int `json:"fs.total.rundown.files"` + HandleDeferredEvictions int `json:"handle.deferred.evictions"` + HandleNameQueryFailures map[string]int `json:"handle.name.query.failures"` + HandleSnapshotCount int `json:"handle.snapshot.count"` + HandleSnapshotBytes int `json:"handle.snapshot.bytes"` + HandleTypesCount int `json:"handle.types.count"` + HandleTypeNameMisses int `json:"handle.type.name.misses"` + HandleWaitTimeouts int `json:"handle.wait.timeouts"` + HostnameErrors map[string]int `json:"hostname.errors"` + CapFlusherErrors map[string]int `json:"cap.flusher.errors"` + CapHandleWriteErrors int `json:"cap.handle.write.errors"` + CapEventUnmarshalErrors int `json:"cap.event.unmarshal.errors"` + CapEventWriteErrors int `json:"cap.event.write.errors"` + CapEventSourceConsumerErrors int `json:"cap.eventsource.consumer.errors"` + CapOverflowErrors int `json:"cap.overflow.errors"` + CapReadBytes int `json:"cap.read.bytes"` + CapReadEvents int `json:"cap.read.events"` + CapReaderDroppedByFilter int `json:"cap.reader.dropped.by.filter"` + CapReaderHandleUnmarshalErrors int `json:"cap.reader.handle.unmarshal.errors"` + EventProcessorFailures int `json:"event.processor.failures"` + EventSeqInitErrors map[string]int `json:"event.seq.init.errors"` + EventSeqStoreErrors int `json:"event.seq.store.errors"` + EventTimestampUnmarshalErrors int `json:"event.timestamp.unmarshal.errors"` + EventSourceBuffersRead int `json:"eventsource.buffers.read"` + EventSourceEventsEnqueued int `json:"eventsource.events.enqueued"` + EventSourceEventsDequeued int `json:"eventsource.events.dequeued"` + EventSourceUnknownEvents int `json:"eventsource.events.unknown"` + EventSourceEventsProcessed int `json:"eventsource.events.processed"` + EventSourceExcludedEvents int `json:"eventsource.excluded.events"` + EventSourceEventsFailures map[string]int `json:"eventsource.events.failures"` + LoggerErrors map[string]int `json:"logger.errors"` + OutputAMQPChannelFailures int `json:"output.amqp.channel.failures"` + OutputAMQPConnectionFailures int `json:"output.amqp.connection.failures"` + OutputAMQPPublishErrors int `json:"output.amqp.publish.errors"` + OutputConsoleErrors int `json:"output.console.errors"` + OutputNullBlackholeEvents int `json:"output.null.blackhole.events"` + PeSkippedImages int `json:"pe.skipped.images"` + PeDirectoryParseErrors int `json:"pe.directory.parse.errors"` + PeVersionResourcesParseErrors int `json:"pe.version.resources.parse.errors"` + ProcessCount int `json:"process.count"` + ProcessModuleCount int `json:"process.module.count"` + ProcessLookupFailureCount map[int]int `json:"process.lookup.failure.count"` + ProcessPebReadErrors int `json:"process.peb.read.errors"` + ProcessReaped int `json:"process.reaped"` + ProcessThreadCount int `json:"process.thread.count"` + RegistryKcbCount int `json:"registry.kcb.count"` + RegistryKcbMisses int `json:"registry.kcb.misses"` + RegistryKeyHandleHits int `json:"registry.key.handle.hits"` + RegistryUnknownKeysCount int `json:"registry.unknown.keys.count"` + StackwalkEnqueued int `json:"stackwalk.enqueued"` + StackwalkFlushes int `json:"stackwalk.flushes"` + StackwalkFlushesProcs map[string]int `json:"stackwalk.flushes.procs"` + StackwalkFlushesEvents map[string]int `json:"stackwalk.flushes.events"` + YaraImageScans int `json:"yara.image.scans"` + YaraProcScans int `json:"yara.proc.scans"` + YaraRuleMatches int `json:"yara.rule.matches"` +} diff --git a/internal/bootstrap/bootstrap.go b/internal/bootstrap/bootstrap_windows.go similarity index 100% rename from internal/bootstrap/bootstrap.go rename to internal/bootstrap/bootstrap_windows.go diff --git a/internal/bootstrap/source.go b/internal/bootstrap/source_windows.go similarity index 100% rename from internal/bootstrap/source.go rename to internal/bootstrap/source_windows.go diff --git a/pkg/aggregator/imports_windows.go b/pkg/aggregator/aggregator_windows.go similarity index 100% rename from pkg/aggregator/imports_windows.go rename to pkg/aggregator/aggregator_windows.go diff --git a/cmd/fibratus/app/config/config_linux.go b/pkg/api/listener_linux.go similarity index 64% rename from cmd/fibratus/app/config/config_linux.go rename to pkg/api/listener_linux.go index 2bd060ba1..a3aa832e2 100644 --- a/cmd/fibratus/app/config/config_linux.go +++ b/pkg/api/listener_linux.go @@ -18,8 +18,17 @@ * limitations under the License. */ -package config +package api -import "github.com/spf13/cobra" +import ( + "context" + "fmt" + "net" +) -var Command = &cobra.Command{Use: "config", Short: "Show runtime config"} +// DialPipe is unavailable on Linux. The HTTP API uses TCP transports instead. +func DialPipe(pipePath string) func(context.Context, string, string) (net.Conn, error) { + return func(context.Context, string, string) (net.Conn, error) { + return nil, fmt.Errorf("named pipe transport %q is not supported on linux", pipePath) + } +} diff --git a/pkg/callstack/callstack.go b/pkg/callstack/callstack_windows.go similarity index 100% rename from pkg/callstack/callstack.go rename to pkg/callstack/callstack_windows.go diff --git a/pkg/util/hostname/hostname_linux.go b/pkg/util/hostname/hostname_linux.go new file mode 100644 index 000000000..a7ae01cc7 --- /dev/null +++ b/pkg/util/hostname/hostname_linux.go @@ -0,0 +1,81 @@ +//go:build linux + +/* + * Copyright 2026 by Mostafa Moradian + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package hostname + +import ( + "expvar" + "net" + "os" +) + +// hostname is the current host name or FQDN +var hostname string + +// hostnameErrors exposes host/fqdn resolution errors +var hostnameErrors = expvar.NewMap("hostname.errors") + +// Get returns the host name of the machine. +func Get() string { + if hostname != "" { + return hostname + } + var err error + hostname, err = os.Hostname() + if err != nil { + hostnameErrors.Add(err.Error(), 1) + } + if hostname == "" { + ip := localIP() + if ip != "" { + hostname = ip + } else { + hostname = "unknown" + } + } + return hostname +} + +// localIP returns the first non-loopback interface IP address. +func localIP() string { + ifaces, err := net.Interfaces() + if err != nil { + return "" + } + for _, i := range ifaces { + addrs, err := i.Addrs() + if err != nil { + continue + } + for _, addr := range addrs { + var ip net.IP + switch v := addr.(type) { + case *net.IPNet: + ip = v.IP + case *net.IPAddr: + ip = v.IP + } + if ip != nil && !ip.IsLoopback() { + return ip.String() + } + } + } + return "" +} From a8de6125979b993c6a14e1d124442a26b0cd435f Mon Sep 17 00:00:00 2001 From: Mostafa Moradian Date: Mon, 10 Aug 2026 16:31:22 +0200 Subject: [PATCH 20/28] fix(cap): Drop Handle and PE capture sections on Linux Those sections are Windows-specific and should not appear in the Linux capture version constants. --- pkg/cap/version/version_linux.go | 9 --------- 1 file changed, 9 deletions(-) diff --git a/pkg/cap/version/version_linux.go b/pkg/cap/version/version_linux.go index 1e1e1aef3..16b420d22 100644 --- a/pkg/cap/version/version_linux.go +++ b/pkg/cap/version/version_linux.go @@ -34,12 +34,3 @@ const ( ProcessSecV3 ProcessSecV4 ) - -const ( - HandleSecV1 Version = iota + 1 -) - -const ( - PESecV1 Version = iota + 1 - PESecV2 -) From d15100cfff293390f78448fd24f1f52362e29516 Mon Sep 17 00:00:00 2001 From: Mostafa Moradian Date: Mon, 10 Aug 2026 16:31:22 +0200 Subject: [PATCH 21/28] refactor(ps): Prefer per-platform Snapshotter interfaces Drop the shared Resolver composition. Linux Snapshotter uses uint64 PIDs, Windows keeps uint32, and event.PID becomes a platform type alias so shared rule/filter call sites stay typed correctly. --- pkg/alertsender/alert.go | 26 ++++----- pkg/alertsender/alert_test.go | 2 + pkg/alertsender/mail/renderer_test.go | 2 + pkg/callstack/callstack_test.go | 2 + pkg/config/filters.go | 2 +- pkg/event/event.go | 2 +- pkg/{ps/resolver.go => event/pid_linux.go} | 11 ++-- pkg/event/pid_windows.go | 24 ++++++++ pkg/filter/accessor_linux.go | 4 +- pkg/filter/accessor_windows.go | 4 +- pkg/filter/filter_linux.go | 6 +- pkg/filter/filter_windows.go | 6 +- pkg/filter/util.go | 4 +- pkg/ps/snapshotter.go | 2 + pkg/ps/snapshotter_linux.go | 67 ++++++++++++++-------- pkg/ps/snapshotter_linux_test.go | 4 +- pkg/ps/snapshotter_mock.go | 2 + pkg/ps/types/types_linux.go | 6 +- pkg/rules/compiler.go | 4 +- pkg/rules/engine.go | 4 +- pkg/rules/engine_linux_test.go | 4 +- pkg/rules/sequence.go | 12 ++-- 22 files changed, 127 insertions(+), 73 deletions(-) rename pkg/{ps/resolver.go => event/pid_linux.go} (82%) create mode 100644 pkg/event/pid_windows.go diff --git a/pkg/alertsender/alert.go b/pkg/alertsender/alert.go index eebb3a43b..988d25f30 100644 --- a/pkg/alertsender/alert.go +++ b/pkg/alertsender/alert.go @@ -182,9 +182,9 @@ func (a Alert) MarshalJSON() ([]byte, error) { Params map[string]any `json:"params"` Callstack []string `json:"callstack,omitempty"` Proc *struct { - PID uint32 `json:"pid"` - TID uint32 `json:"tid"` - PPID uint32 `json:"ppid"` + PID event.PID `json:"pid"` + TID uint32 `json:"tid"` + PPID event.PID `json:"ppid"` Name string `json:"name"` Exe string `json:"exe"` Cmdline string `json:"cmdline,omitempty"` @@ -218,9 +218,9 @@ func (a Alert) MarshalJSON() ([]byte, error) { Params map[string]any `json:"params"` Callstack []string `json:"callstack,omitempty"` Proc *struct { - PID uint32 `json:"pid"` - TID uint32 `json:"tid"` - PPID uint32 `json:"ppid"` + PID event.PID `json:"pid"` + TID uint32 `json:"tid"` + PPID event.PID `json:"ppid"` Name string `json:"name"` Exe string `json:"exe"` Cmdline string `json:"cmdline,omitempty"` @@ -247,9 +247,9 @@ func (a Alert) MarshalJSON() ([]byte, error) { Params map[string]any `json:"params"` Callstack []string `json:"callstack,omitempty"` Proc *struct { - PID uint32 `json:"pid"` - TID uint32 `json:"tid"` - PPID uint32 `json:"ppid"` + PID event.PID `json:"pid"` + TID uint32 `json:"tid"` + PPID event.PID `json:"ppid"` Name string `json:"name"` Exe string `json:"exe"` Cmdline string `json:"cmdline,omitempty"` @@ -287,15 +287,15 @@ func (a Alert) MarshalJSON() ([]byte, error) { // populate callstack for i := range e.Callstack { frame := e.Callstack[len(e.Callstack)-i-1] - evt.Callstack = append(evt.Callstack, fmt.Sprintf("%s %s!%s", frame.Addr, frame.Module, frame.Symbol)) + evt.Callstack = append(evt.Callstack, fmt.Sprintf("%v %s!%s", frame.Addr, frame.Module, frame.Symbol)) } ps := e.PS if ps != nil { evt.Proc = &struct { - PID uint32 `json:"pid"` - TID uint32 `json:"tid"` - PPID uint32 `json:"ppid"` + PID event.PID `json:"pid"` + TID uint32 `json:"tid"` + PPID event.PID `json:"ppid"` Name string `json:"name"` Exe string `json:"exe"` Cmdline string `json:"cmdline,omitempty"` diff --git a/pkg/alertsender/alert_test.go b/pkg/alertsender/alert_test.go index 2e7b5b08d..d55ac350a 100644 --- a/pkg/alertsender/alert_test.go +++ b/pkg/alertsender/alert_test.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2021-2022 by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/pkg/alertsender/mail/renderer_test.go b/pkg/alertsender/mail/renderer_test.go index 751244347..8c9835b8e 100644 --- a/pkg/alertsender/mail/renderer_test.go +++ b/pkg/alertsender/mail/renderer_test.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2021-2022 by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/pkg/callstack/callstack_test.go b/pkg/callstack/callstack_test.go index 7002052fc..9cf9c4cea 100644 --- a/pkg/callstack/callstack_test.go +++ b/pkg/callstack/callstack_test.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2021-present by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/pkg/config/filters.go b/pkg/config/filters.go index 3d0bdfe5e..e9eb3cffb 100644 --- a/pkg/config/filters.go +++ b/pkg/config/filters.go @@ -176,7 +176,7 @@ func (ctx *ActionContext) UniquePids() []uint32 { if e.IsCreateProcess() { pids[e.Params.MustGetPid()] = struct{}{} } else { - pids[e.PID] = struct{}{} + pids[uint32(e.PID)] = struct{}{} } } return convert.MapKeysToSlice(pids) diff --git a/pkg/event/event.go b/pkg/event/event.go index 66ca2905c..336ec7dc3 100644 --- a/pkg/event/event.go +++ b/pkg/event/event.go @@ -74,7 +74,7 @@ type Event struct { // Timestamp represents the temporal occurrence of the event. Timestamp time.Time `json:"timestamp"` // PID is the identifier of the process that generated the event. - PID uint32 `json:"pid"` + PID PID `json:"pid"` // Tid is the thread identifier of the thread that generated the event. Tid uint32 `json:"tid"` // Evasions is the bitmask that stores detected evasion types on this event. diff --git a/pkg/ps/resolver.go b/pkg/event/pid_linux.go similarity index 82% rename from pkg/ps/resolver.go rename to pkg/event/pid_linux.go index 4f3e07d9b..340f0367a 100644 --- a/pkg/ps/resolver.go +++ b/pkg/event/pid_linux.go @@ -1,3 +1,5 @@ +//go:build linux + /* * Copyright 2026 by Mostafa Moradian * https://www.fibratus.io @@ -16,10 +18,7 @@ * limitations under the License. */ -package ps - -import pstypes "github.com/rabbitstack/fibratus/pkg/ps/types" +package event -type Resolver interface { - Find(pid uint32) (bool, *pstypes.PS) -} +// PID is the process identifier type on Linux (kernel PIDs are 64-bit). +type PID = uint64 diff --git a/pkg/event/pid_windows.go b/pkg/event/pid_windows.go new file mode 100644 index 000000000..a93a7dc04 --- /dev/null +++ b/pkg/event/pid_windows.go @@ -0,0 +1,24 @@ +//go:build windows + +/* + * Copyright 2026 by Mostafa Moradian + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package event + +// PID is the process identifier type on Windows. +type PID = uint32 diff --git a/pkg/filter/accessor_linux.go b/pkg/filter/accessor_linux.go index 59ceb97b7..069271f0d 100644 --- a/pkg/filter/accessor_linux.go +++ b/pkg/filter/accessor_linux.go @@ -36,7 +36,7 @@ func GetAccessors() []Accessor { } type psAccessor struct { - psnap ps.Resolver + psnap ps.Snapshotter } func (psAccessor) SetFields([]Field) {} @@ -45,7 +45,7 @@ func (psAccessor) IsFieldAccessible(e *event.Event) bool { return e.PS != nil || e.Category == event.Process } -func newPSAccessor(psnap ps.Resolver) Accessor { return &psAccessor{psnap: psnap} } +func newPSAccessor(psnap ps.Snapshotter) Accessor { return &psAccessor{psnap: psnap} } func (a *psAccessor) Get(f Field, e *event.Event) (params.Value, error) { switch f.Name { diff --git a/pkg/filter/accessor_windows.go b/pkg/filter/accessor_windows.go index 79c1f0d4c..25e60ee7e 100644 --- a/pkg/filter/accessor_windows.go +++ b/pkg/filter/accessor_windows.go @@ -72,7 +72,7 @@ func getParentPs(e *event.Event) *pstypes.PS { // psAccessor extracts process's state or event specific values. type psAccessor struct { - psnap psnap.Resolver + psnap psnap.Snapshotter } func (psAccessor) SetFields([]Field) {} @@ -81,7 +81,7 @@ func (psAccessor) IsFieldAccessible(e *event.Event) bool { return e.PS != nil || e.Category == event.Process } -func newPSAccessor(psnap psnap.Resolver) Accessor { return &psAccessor{psnap: psnap} } +func newPSAccessor(psnap psnap.Snapshotter) Accessor { return &psAccessor{psnap: psnap} } func (ps *psAccessor) Get(f Field, e *event.Event) (params.Value, error) { switch f.Name { diff --git a/pkg/filter/filter_linux.go b/pkg/filter/filter_linux.go index 42ad1eb0a..a5c7d6cff 100644 --- a/pkg/filter/filter_linux.go +++ b/pkg/filter/filter_linux.go @@ -31,14 +31,14 @@ import ( ) type opts struct { - psnap ps.Resolver + psnap ps.Snapshotter } // Option defines the option supplied to the filter type Option func(o *opts) -// WithPSnapshotter passes a process resolver reference to the filter. -func WithPSnapshotter(psnap ps.Resolver) Option { +// WithPSnapshotter passes a process snapshotter reference to the filter. +func WithPSnapshotter(psnap ps.Snapshotter) Option { return func(o *opts) { o.psnap = psnap } diff --git a/pkg/filter/filter_windows.go b/pkg/filter/filter_windows.go index ce36e657a..d2a0ea1fa 100644 --- a/pkg/filter/filter_windows.go +++ b/pkg/filter/filter_windows.go @@ -29,14 +29,14 @@ import ( ) type opts struct { - psnap ps.Resolver + psnap ps.Snapshotter } // Option defines the option supplied to the filter type Option func(o *opts) -// WithPSnapshotter passes a process resolver reference to the filter. -func WithPSnapshotter(psnap ps.Resolver) Option { +// WithPSnapshotter passes a process snapshotter reference to the filter. +func WithPSnapshotter(psnap ps.Snapshotter) Option { return func(o *opts) { o.psnap = psnap } diff --git a/pkg/filter/util.go b/pkg/filter/util.go index f5562a40a..700b07d07 100644 --- a/pkg/filter/util.go +++ b/pkg/filter/util.go @@ -28,9 +28,9 @@ import ( ) // framePID returns the pid associated with the stack frame. -func framePID(e *event.Event) uint32 { +func framePID(e *event.Event) event.PID { if !e.Callstack.IsEmpty() && e.Callstack.FrameAt(0).PID != 0 { - return e.Callstack.FrameAt(0).PID + return event.PID(e.Callstack.FrameAt(0).PID) } return e.PID } diff --git a/pkg/ps/snapshotter.go b/pkg/ps/snapshotter.go index f58f45403..34f7997fa 100644 --- a/pkg/ps/snapshotter.go +++ b/pkg/ps/snapshotter.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2020-2021 by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/pkg/ps/snapshotter_linux.go b/pkg/ps/snapshotter_linux.go index 0b4f9d9cf..37b049397 100644 --- a/pkg/ps/snapshotter_linux.go +++ b/pkg/ps/snapshotter_linux.go @@ -28,39 +28,60 @@ import ( "github.com/rabbitstack/fibratus/pkg/util/va" ) -// LinuxSnapshotter stores Linux process state for enrichment and rule evaluation. -type LinuxSnapshotter interface { - Resolver +// Snapshotter stores Linux process state for enrichment and rule evaluation. +type Snapshotter interface { + // Write appends or updates process state from an inbound event. Write(*event.Event) error + // Remove deletes process state for the event process identifier. Remove(*event.Event) error - UpsertSnapshot(*pstypes.PS) + // Find attempts to retrieve process state for the specified process identifier. + Find(pid uint64) (bool, *pstypes.PS) + // FindAndPut attempts to retrieve process state and updates the snapshot when found. + FindAndPut(pid uint64) *pstypes.PS + // Put inserts the process state into the snapshotter. Put(*pstypes.PS) + // UpsertSnapshot inserts or replaces process state. + UpsertSnapshot(*pstypes.PS) + // Size returns the total number of process state items. Size() uint32 + // Close closes the process snapshotter and disposes allocated resources. Close() error + // AddThread builds thread state from the event representation. AddThread(*event.Event) error - RemoveThread(pid uint32, tid uint32) error + // RemoveThread removes the thread from the given process. + RemoveThread(pid uint64, tid uint32) error + // AddMmap adds a memory mapping to the process state. AddMmap(*event.Event) error - RemoveMmap(pid uint32, addr va.Address) error + // RemoveMmap removes a memory mapping at the given base address. + RemoveMmap(pid uint64, addr va.Address) error } -type linuxSnapshotter struct { +type snapshotter struct { mu sync.RWMutex - procs map[uint32]*pstypes.PS + procs map[uint64]*pstypes.PS } -// NewLinuxSnapshotter builds an in-memory Linux process snapshotter. -func NewLinuxSnapshotter() LinuxSnapshotter { - return &linuxSnapshotter{procs: make(map[uint32]*pstypes.PS)} +// NewSnapshotter builds an in-memory Linux process snapshotter. +func NewSnapshotter() Snapshotter { + return &snapshotter{procs: make(map[uint64]*pstypes.PS)} } -func (s *linuxSnapshotter) Find(pid uint32) (bool, *pstypes.PS) { +func (s *snapshotter) Find(pid uint64) (bool, *pstypes.PS) { s.mu.RLock() defer s.mu.RUnlock() ps, ok := s.procs[pid] return ok, ps } -func (s *linuxSnapshotter) Put(ps *pstypes.PS) { +func (s *snapshotter) FindAndPut(pid uint64) *pstypes.PS { + ok, ps := s.Find(pid) + if !ok { + return nil + } + return ps +} + +func (s *snapshotter) Put(ps *pstypes.PS) { if ps == nil { return } @@ -69,11 +90,11 @@ func (s *linuxSnapshotter) Put(ps *pstypes.PS) { s.procs[ps.PID] = ps } -func (s *linuxSnapshotter) UpsertSnapshot(ps *pstypes.PS) { +func (s *snapshotter) UpsertSnapshot(ps *pstypes.PS) { s.Put(ps) } -func (s *linuxSnapshotter) Write(evt *event.Event) error { +func (s *snapshotter) Write(evt *event.Event) error { if evt == nil || evt.PS == nil { return nil } @@ -81,7 +102,7 @@ func (s *linuxSnapshotter) Write(evt *event.Event) error { return nil } -func (s *linuxSnapshotter) Remove(evt *event.Event) error { +func (s *snapshotter) Remove(evt *event.Event) error { if evt == nil { return nil } @@ -91,20 +112,20 @@ func (s *linuxSnapshotter) Remove(evt *event.Event) error { return nil } -func (s *linuxSnapshotter) Size() uint32 { +func (s *snapshotter) Size() uint32 { s.mu.RLock() defer s.mu.RUnlock() return uint32(len(s.procs)) } -func (s *linuxSnapshotter) Close() error { +func (s *snapshotter) Close() error { s.mu.Lock() defer s.mu.Unlock() - s.procs = make(map[uint32]*pstypes.PS) + s.procs = make(map[uint64]*pstypes.PS) return nil } -func (s *linuxSnapshotter) AddThread(evt *event.Event) error { +func (s *snapshotter) AddThread(evt *event.Event) error { if evt == nil || evt.PS == nil { return nil } @@ -117,7 +138,7 @@ func (s *linuxSnapshotter) AddThread(evt *event.Event) error { return nil } -func (s *linuxSnapshotter) RemoveThread(pid uint32, tid uint32) error { +func (s *snapshotter) RemoveThread(pid uint64, tid uint32) error { ok, ps := s.Find(pid) if !ok || ps == nil { return nil @@ -126,7 +147,7 @@ func (s *linuxSnapshotter) RemoveThread(pid uint32, tid uint32) error { return nil } -func (s *linuxSnapshotter) AddMmap(evt *event.Event) error { +func (s *snapshotter) AddMmap(evt *event.Event) error { if evt == nil || evt.PS == nil { return nil } @@ -141,7 +162,7 @@ func (s *linuxSnapshotter) AddMmap(evt *event.Event) error { return nil } -func (s *linuxSnapshotter) RemoveMmap(pid uint32, addr va.Address) error { +func (s *snapshotter) RemoveMmap(pid uint64, addr va.Address) error { ok, ps := s.Find(pid) if !ok || ps == nil { return nil diff --git a/pkg/ps/snapshotter_linux_test.go b/pkg/ps/snapshotter_linux_test.go index 1c6b178b1..06b10181f 100644 --- a/pkg/ps/snapshotter_linux_test.go +++ b/pkg/ps/snapshotter_linux_test.go @@ -29,8 +29,8 @@ import ( "github.com/stretchr/testify/require" ) -func TestLinuxSnapshotterFindPut(t *testing.T) { - s := NewLinuxSnapshotter() +func TestSnapshotterFindPut(t *testing.T) { + s := NewSnapshotter() ps := &pstypes.PS{PID: 100, Name: "bash", StartBootTime: 1234} s.Put(ps) diff --git a/pkg/ps/snapshotter_mock.go b/pkg/ps/snapshotter_mock.go index 2b3dade65..b6f38c314 100644 --- a/pkg/ps/snapshotter_mock.go +++ b/pkg/ps/snapshotter_mock.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2019-2020 by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/pkg/ps/types/types_linux.go b/pkg/ps/types/types_linux.go index d52196646..d70a71ffc 100644 --- a/pkg/ps/types/types_linux.go +++ b/pkg/ps/types/types_linux.go @@ -38,8 +38,8 @@ func (p *PE) String() string { return "" } type PS struct { sync.RWMutex - PID uint32 `json:"pid"` - Ppid uint32 `json:"ppid"` + PID uint64 `json:"pid"` + Ppid uint64 `json:"ppid"` Name string `json:"name"` Cmdline string `json:"comm"` Exe string `json:"exe"` @@ -85,7 +85,7 @@ func (ps *PS) Ancestors() []string { type Thread struct { Tid uint32 - Pid uint32 + Pid uint64 StartAddress va.Address UstackBase va.Address UstackLimit va.Address diff --git a/pkg/rules/compiler.go b/pkg/rules/compiler.go index f7945b0ec..d0c107df3 100644 --- a/pkg/rules/compiler.go +++ b/pkg/rules/compiler.go @@ -58,12 +58,12 @@ var ( ) type compiler struct { - psnap ps.Resolver + psnap ps.Snapshotter config *config.Config approvers config.Approvers } -func newCompiler(psnap ps.Resolver, cfg *config.Config) *compiler { +func newCompiler(psnap ps.Snapshotter, cfg *config.Config) *compiler { return &compiler{psnap: psnap, config: cfg, approvers: config.Approvers{ Keys: make(map[string][]string), Paths: make(map[string][]string), diff --git a/pkg/rules/engine.go b/pkg/rules/engine.go index a6cce31df..cd0f4974a 100644 --- a/pkg/rules/engine.go +++ b/pkg/rules/engine.go @@ -55,7 +55,7 @@ var ( type Engine struct { filters *filterset config *config.Config - psnap ps.Resolver + psnap ps.Snapshotter matches []*ruleMatch mmu sync.Mutex // guards the rule matches slice @@ -130,7 +130,7 @@ func (f *compiledFilter) eval(e *event.Event, valuer *filter.ValuerCache) bool { } // NewEngine builds a fresh rules engine instance. -func NewEngine(psnap ps.Resolver, config *config.Config) *Engine { +func NewEngine(psnap ps.Snapshotter, config *config.Config) *Engine { e := &Engine{ filters: newFilterset(), matches: make([]*ruleMatch, 0), diff --git a/pkg/rules/engine_linux_test.go b/pkg/rules/engine_linux_test.go index 59c26b68d..5d514a30f 100644 --- a/pkg/rules/engine_linux_test.go +++ b/pkg/rules/engine_linux_test.go @@ -28,9 +28,9 @@ import ( "github.com/stretchr/testify/require" ) -func TestNewEngineAcceptsResolver(t *testing.T) { +func TestNewEngineAcceptsSnapshotter(t *testing.T) { cfg := &config.Config{Filters: &config.Filters{}} - e := NewEngine(ps.NewLinuxSnapshotter(), cfg) + e := NewEngine(ps.NewSnapshotter(), cfg) require.NotNil(t, e) require.NotNil(t, e.compiler) } diff --git a/pkg/rules/sequence.go b/pkg/rules/sequence.go index 9015c8eaa..d6cc20a90 100644 --- a/pkg/rules/sequence.go +++ b/pkg/rules/sequence.go @@ -120,10 +120,10 @@ type sequenceState struct { // The purpose is to enforce temporal monotonicity lastMatch time.Time - psnap ps.Resolver + psnap ps.Snapshotter } -func newSequenceState(f filter.Filter, c *config.FilterConfig, psnap ps.Resolver) *sequenceState { +func newSequenceState(f filter.Filter, c *config.FilterConfig, psnap ps.Snapshotter) *sequenceState { ss := &sequenceState{ filter: f, seq: f.GetSequence(), @@ -566,17 +566,17 @@ func (s *sequenceState) expire(e *event.Event) bool { // process spawned by CreateProcess, and it pertains // to the final sequence slot, it is safe to expire // the whole sequence - pid := rhs.Params.MustGetPid() + pid := event.PID(rhs.Params.MustGetPid()) if lhs.Type == event.CreateProcess && isFinalSlot { - return lhs.Params.MustGetPid() == pid + return event.PID(lhs.Params.MustGetPid()) == pid } if lhs.Type == event.CreateThread { // if the pids differ, the thread // is created in a remote process. // Sequence can be expired only if // the remote process terminates - if lhs.PID != lhs.Params.MustGetPid() { - return lhs.Params.MustGetPid() == pid + if lhs.PID != event.PID(lhs.Params.MustGetPid()) { + return event.PID(lhs.Params.MustGetPid()) == pid } } return lhs.PID == pid From c9c2f02251ac248d00e1a0e41fcb8bfa642a3be6 Mon Sep 17 00:00:00 2001 From: Mostafa Moradian Date: Mon, 10 Aug 2026 16:31:23 +0200 Subject: [PATCH 22/28] refactor(config): Split alertsender loading by platform Keep mail and Slack loading shared, and move systray/eventlog loading into the Windows-specific path. Linux Config now stores Alertsenders for the shared loader. --- pkg/config/alertsender.go | 47 ++++++------------------- pkg/config/alertsender_linux.go | 31 +++++++++++++++++ pkg/config/alertsender_windows.go | 58 +++++++++++++++++++++++++++++++ pkg/config/config_linux.go | 19 ++++++---- 4 files changed, 111 insertions(+), 44 deletions(-) create mode 100644 pkg/config/alertsender_linux.go create mode 100644 pkg/config/alertsender_windows.go diff --git a/pkg/config/alertsender.go b/pkg/config/alertsender.go index 237b3fe97..5abc11343 100644 --- a/pkg/config/alertsender.go +++ b/pkg/config/alertsender.go @@ -1,7 +1,6 @@ -//go:build windows - /* * Copyright 2019-2020 by Nedim Sabic Sabic + * Copyright 2026 by Mostafa Moradian * https://www.fibratus.io * All Rights Reserved. * @@ -23,12 +22,11 @@ package config import ( "errors" "fmt" + "reflect" + "github.com/rabbitstack/fibratus/pkg/alertsender" - "github.com/rabbitstack/fibratus/pkg/alertsender/eventlog" "github.com/rabbitstack/fibratus/pkg/alertsender/mail" "github.com/rabbitstack/fibratus/pkg/alertsender/slack" - "github.com/rabbitstack/fibratus/pkg/alertsender/systray" - "reflect" ) var errNoAlertsendersSection = errors.New("no alertsenders section in config") @@ -64,11 +62,10 @@ func (c *Config) tryLoadAlertSenders() error { if !mailConfig.Enabled { continue } - config := alertsender.Config{ + configs = append(configs, alertsender.Config{ Type: alertsender.Mail, Sender: mailConfig, - } - configs = append(configs, config) + }) case "slack": var slackConfig slack.Config if err := decode(config, &slackConfig); err != nil { @@ -77,38 +74,14 @@ func (c *Config) tryLoadAlertSenders() error { if !slackConfig.Enabled { continue } - config := alertsender.Config{ + configs = append(configs, alertsender.Config{ Type: alertsender.Slack, Sender: slackConfig, + }) + default: + if err := c.loadPlatformAlertSender(typ, config, &configs); err != nil { + return err } - configs = append(configs, config) - case "systray": - var systrayConfig systray.Config - if err := decode(config, &systrayConfig); err != nil { - return errAlertsenderConfig(typ, err) - } - if !systrayConfig.Enabled { - continue - } - config := alertsender.Config{ - Type: alertsender.Systray, - Sender: systrayConfig, - } - configs = append(configs, config) - - case "eventlog": - var eventlogConfig eventlog.Config - if err := decode(config, &eventlogConfig); err != nil { - return errAlertsenderConfig(typ, err) - } - if !eventlogConfig.Enabled { - continue - } - config := alertsender.Config{ - Type: alertsender.Eventlog, - Sender: eventlogConfig, - } - configs = append(configs, config) } } diff --git a/pkg/config/alertsender_linux.go b/pkg/config/alertsender_linux.go new file mode 100644 index 000000000..1818cc7f1 --- /dev/null +++ b/pkg/config/alertsender_linux.go @@ -0,0 +1,31 @@ +//go:build linux + +/* + * Copyright 2026 by Mostafa Moradian + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package config + +import "github.com/rabbitstack/fibratus/pkg/alertsender" + +func (c *Config) loadPlatformAlertSender(typ string, config interface{}, configs *[]alertsender.Config) error { + // Platform-specific Linux alert senders can be loaded here. + _ = typ + _ = config + _ = configs + return nil +} diff --git a/pkg/config/alertsender_windows.go b/pkg/config/alertsender_windows.go new file mode 100644 index 000000000..83eaf8cc1 --- /dev/null +++ b/pkg/config/alertsender_windows.go @@ -0,0 +1,58 @@ +//go:build windows + +/* + * Copyright 2019-2020 by Nedim Sabic Sabic + * Copyright 2026 by Mostafa Moradian + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package config + +import ( + "github.com/rabbitstack/fibratus/pkg/alertsender" + "github.com/rabbitstack/fibratus/pkg/alertsender/eventlog" + "github.com/rabbitstack/fibratus/pkg/alertsender/systray" +) + +func (c *Config) loadPlatformAlertSender(typ string, config interface{}, configs *[]alertsender.Config) error { + switch typ { + case "systray": + var systrayConfig systray.Config + if err := decode(config, &systrayConfig); err != nil { + return errAlertsenderConfig(typ, err) + } + if !systrayConfig.Enabled { + return nil + } + *configs = append(*configs, alertsender.Config{ + Type: alertsender.Systray, + Sender: systrayConfig, + }) + case "eventlog": + var eventlogConfig eventlog.Config + if err := decode(config, &eventlogConfig); err != nil { + return errAlertsenderConfig(typ, err) + } + if !eventlogConfig.Enabled { + return nil + } + *configs = append(*configs, alertsender.Config{ + Type: alertsender.Eventlog, + Sender: eventlogConfig, + }) + } + return nil +} diff --git a/pkg/config/config_linux.go b/pkg/config/config_linux.go index c0295c0a0..c00e1190c 100644 --- a/pkg/config/config_linux.go +++ b/pkg/config/config_linux.go @@ -25,6 +25,7 @@ import ( "path/filepath" "strings" + "github.com/rabbitstack/fibratus/pkg/alertsender" "github.com/rabbitstack/fibratus/pkg/util/log" "github.com/spf13/cobra" "github.com/spf13/pflag" @@ -34,13 +35,14 @@ import ( const configFile = "config-file" type Config struct { - EventSource EventSourceConfig `json:"eventsource" yaml:"eventsource"` - Filament FilamentConfig `json:"filament" yaml:"filament"` - API APIConfig `json:"api" yaml:"api"` - Log log.Config `json:"logging" yaml:"logging"` - Filters *Filters `json:"filters" yaml:"filters"` - ForwardMode bool `json:"forward" yaml:"forward"` - CapFile string `json:"cap.file" yaml:"cap.file"` + EventSource EventSourceConfig `json:"eventsource" yaml:"eventsource"` + Filament FilamentConfig `json:"filament" yaml:"filament"` + API APIConfig `json:"api" yaml:"api"` + Log log.Config `json:"logging" yaml:"logging"` + Filters *Filters `json:"filters" yaml:"filters"` + ForwardMode bool `json:"forward" yaml:"forward"` + CapFile string `json:"cap.file" yaml:"cap.file"` + Alertsenders []alertsender.Config `json:"-" yaml:"-"` flags *pflag.FlagSet viper *viper.Viper @@ -104,6 +106,9 @@ func (c *Config) Init() error { c.Filters.initFromViper(c.viper) c.ForwardMode = c.viper.GetBool("forward") c.CapFile = c.viper.GetString("cap.file") + if err := c.tryLoadAlertSenders(); err != nil && err != errNoAlertsendersSection { + return err + } return nil } From ce1f8af360179f7625380d82871c74b7737e08c6 Mon Sep 17 00:00:00 2001 From: Mostafa Moradian Date: Mon, 10 Aug 2026 23:36:27 +0200 Subject: [PATCH 23/28] refactor(config): share platform-neutral configuration Move common config, event-source, output, schema, transformer, and validation behavior into shared files while retaining platform-specific hooks. Add Linux schema coverage and preserve Windows callers through explicit platform field assignment. --- internal/etw/source_test.go | 18 +- pkg/config/alertsender_linux_test.go | 59 +++ pkg/config/config.go | 258 +++++++++++ pkg/config/config.schema.json | 9 + pkg/config/config_linux.go | 112 +---- pkg/config/config_windows.go | 430 +++--------------- pkg/config/eventsource.go | 174 +------ pkg/config/eventsource_linux.go | 43 +- pkg/config/eventsource_linux_test.go | 71 +++ pkg/config/eventsource_windows.go | 126 +++++ pkg/config/output.go | 36 +- .../{schema_linux.go => output_linux.go} | 12 +- pkg/config/output_linux_test.go | 38 ++ pkg/config/output_test.go | 22 - pkg/config/output_windows.go | 58 +++ pkg/config/output_windows_test.go | 41 ++ pkg/config/print_test.go | 7 +- pkg/config/{schema_windows.go => schema.go} | 4 +- pkg/config/transformer.go | 5 +- pkg/config/transformer_test.go | 5 +- pkg/handle/snapshotter_test.go | 9 +- pkg/symbolize/symbolizer_test.go | 8 +- 22 files changed, 798 insertions(+), 747 deletions(-) create mode 100644 pkg/config/alertsender_linux_test.go create mode 100644 pkg/config/config.go create mode 100644 pkg/config/eventsource_linux_test.go create mode 100644 pkg/config/eventsource_windows.go rename pkg/config/{schema_linux.go => output_linux.go} (73%) create mode 100644 pkg/config/output_linux_test.go create mode 100644 pkg/config/output_windows.go create mode 100644 pkg/config/output_windows_test.go rename pkg/config/{schema_windows.go => schema.go} (97%) diff --git a/internal/etw/source_test.go b/internal/etw/source_test.go index c4b3241a8..765019ab5 100644 --- a/internal/etw/source_test.go +++ b/internal/etw/source_test.go @@ -274,12 +274,12 @@ func TestEventSourceEnableFlagsDynamicallyWithYaraEnabled(t *testing.T) { EnableMemEvents: true, }, Filters: &config.Filters{}, - Yara: yara.Config{ - Enabled: true, - SkipFiles: false, - SkipMmaps: true, - SkipAllocs: false, - }, + } + cfg.Yara = yara.Config{ + Enabled: true, + SkipFiles: false, + SkipMmaps: true, + SkipAllocs: false, } cfg.EventSource.Init() @@ -1139,10 +1139,10 @@ func testCallstackEnrichment(t *testing.T, hsnap handle.Snapshotter, psnap ps.Sn evsConfig.Init() cfg := &config.Config{ - EventSource: evsConfig, - Filters: &config.Filters{}, - SymbolizeKernelAddresses: true, + EventSource: evsConfig, + Filters: &config.Filters{}, } + cfg.SymbolizeKernelAddresses = true evs := NewEventSource(psnap, hsnap, cfg, nil) symbolizer := symbolize.NewSymbolizer(symbolize.NewDebugHelpResolver(cfg), psnap, cfg, true) diff --git a/pkg/config/alertsender_linux_test.go b/pkg/config/alertsender_linux_test.go new file mode 100644 index 000000000..d48b3c364 --- /dev/null +++ b/pkg/config/alertsender_linux_test.go @@ -0,0 +1,59 @@ +//go:build linux + +/* + * Copyright 2026 by Mostafa Moradian + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package config + +import ( + "testing" + + "github.com/rabbitstack/fibratus/pkg/alertsender" + "github.com/rabbitstack/fibratus/pkg/alertsender/mail" + "github.com/rabbitstack/fibratus/pkg/alertsender/slack" + "github.com/stretchr/testify/require" +) + +func TestAlertSendersLinux(t *testing.T) { + c := NewWithOpts(WithRun()) + c.viper.Set("alertsenders", map[string]interface{}{ + "mail": map[string]interface{}{ + "enabled": true, + "host": "smtp.example.com", + }, + "slack": map[string]interface{}{ + "enabled": true, + "url": "https://example.com/hook", + }, + "eventlog": map[string]interface{}{"enabled": true}, + "systray": map[string]interface{}{"enabled": true}, + }) + + require.NoError(t, c.tryLoadAlertSenders()) + require.Len(t, c.Alertsenders, 2) + for _, sender := range c.Alertsenders { + switch sender.Type { + case alertsender.Mail: + require.IsType(t, mail.Config{}, sender.Sender) + case alertsender.Slack: + require.IsType(t, slack.Config{}, sender.Sender) + default: + require.Failf(t, "unexpected sender", "%v", sender.Type) + } + } +} diff --git a/pkg/config/config.go b/pkg/config/config.go new file mode 100644 index 000000000..534f97802 --- /dev/null +++ b/pkg/config/config.go @@ -0,0 +1,258 @@ +/* + * Copyright 2019-2020 by Nedim Sabic Sabic + * Copyright 2026 by Mostafa Moradian + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package config + +import ( + "encoding/json" + "fmt" + "os" + "path/filepath" + "strings" + "time" + + "github.com/rabbitstack/fibratus/pkg/aggregator" + "github.com/rabbitstack/fibratus/pkg/aggregator/transformers" + removet "github.com/rabbitstack/fibratus/pkg/aggregator/transformers/remove" + renamet "github.com/rabbitstack/fibratus/pkg/aggregator/transformers/rename" + replacet "github.com/rabbitstack/fibratus/pkg/aggregator/transformers/replace" + tagst "github.com/rabbitstack/fibratus/pkg/aggregator/transformers/tags" + trimt "github.com/rabbitstack/fibratus/pkg/aggregator/transformers/trim" + "github.com/rabbitstack/fibratus/pkg/alertsender" + mailsender "github.com/rabbitstack/fibratus/pkg/alertsender/mail" + slacksender "github.com/rabbitstack/fibratus/pkg/alertsender/slack" + "github.com/rabbitstack/fibratus/pkg/outputs" + "github.com/rabbitstack/fibratus/pkg/outputs/amqp" + "github.com/rabbitstack/fibratus/pkg/outputs/console" + "github.com/rabbitstack/fibratus/pkg/outputs/elasticsearch" + "github.com/rabbitstack/fibratus/pkg/outputs/http" + "github.com/rabbitstack/fibratus/pkg/util/log" + "github.com/rabbitstack/fibratus/pkg/util/multierror" + "github.com/spf13/cobra" + "github.com/spf13/pflag" + "github.com/spf13/viper" + "gopkg.in/yaml.v3" +) + +const ( + capFile = "cap.file" + configFile = "config-file" + forwardMode = "forward" +) + +// Config stores configuration options for fine-tuning the behaviour of Fibratus. +type Config struct { + platformConfig + + EventSource EventSourceConfig `json:"eventsource" yaml:"eventsource"` + Filament FilamentConfig `json:"filament" yaml:"filament"` + API APIConfig `json:"api" yaml:"api"` + Output outputs.Config + Aggregator aggregator.Config `json:"aggregator" yaml:"aggregator"` + Log log.Config `json:"logging" yaml:"logging"` + Transformers []transformers.Config + Alertsenders []alertsender.Config + Filters *Filters `json:"filters" yaml:"filters"` + ForwardMode bool `json:"forward" yaml:"forward"` + CapFile string + + flags *pflag.FlagSet + viper *viper.Viper + opts *Options +} + +// Options determines which config flags are toggled depending on the command type. +type Options struct { + capture bool + replay bool + run bool + list bool + stats bool + validate bool +} + +// Option configures the command-specific configuration surface. +type Option func(*Options) + +func WithCapture() Option { return func(o *Options) { o.capture = true } } +func WithReplay() Option { return func(o *Options) { o.replay = true } } +func WithRun() Option { return func(o *Options) { o.run = true } } +func WithList() Option { return func(o *Options) { o.list = true } } +func WithStats() Option { return func(o *Options) { o.stats = true } } +func WithValidate() Option { return func(o *Options) { o.validate = true } } + +// NewWithOpts builds a new configuration store from files, environment variables, and flags. +func NewWithOpts(options ...Option) *Config { + opts := &Options{} + for _, option := range options { + option(opts) + } + + v := viper.New() + v.AutomaticEnv() + v.SetEnvKeyReplacer(strings.NewReplacer("-", "_", ".", "_")) + + c := &Config{ + platformConfig: newPlatformConfig(), + EventSource: EventSourceConfig{}, + Filament: FilamentConfig{}, + API: APIConfig{}, + Aggregator: aggregator.Config{}, + Log: log.Config{}, + Filters: &Filters{}, + flags: new(pflag.FlagSet), + viper: v, + opts: opts, + } + + if opts.run || opts.replay { + aggregator.AddFlags(c.flags) + console.AddFlags(c.flags) + amqp.AddFlags(c.flags) + elasticsearch.AddFlags(c.flags) + http.AddFlags(c.flags) + removet.AddFlags(c.flags) + replacet.AddFlags(c.flags) + renamet.AddFlags(c.flags) + trimt.AddFlags(c.flags) + tagst.AddFlags(c.flags) + mailsender.AddFlags(c.flags) + slacksender.AddFlags(c.flags) + } + + c.addFlags() + c.addPlatformFlags() + return c +} + +// MustViperize adds the configuration flags to the Cobra command. +func (c *Config) MustViperize(cmd *cobra.Command) { + cmd.PersistentFlags().AddFlagSet(c.flags) + if err := c.viper.BindPFlags(cmd.PersistentFlags()); err != nil { + panic(err) + } + if c.opts.capture || c.opts.replay { + if err := cmd.MarkPersistentFlagRequired(capFile); err != nil { + panic(err) + } + } +} + +// Init initializes the configuration state from Viper. +func (c *Config) Init() error { + c.EventSource.initFromViper(c.viper) + c.Filament.initFromViper(c.viper) + c.API.initFromViper(c.viper) + c.Aggregator.InitFromViper(c.viper) + c.Log.InitFromViper(c.viper) + c.Filters.initFromViper(c.viper) + c.ForwardMode = c.viper.GetBool(forwardMode) + c.CapFile = c.viper.GetString(capFile) + c.initPlatform() + + if c.opts.run || c.opts.replay { + if err := c.tryLoadOutput(); err != nil { + return err + } + if err := c.tryLoadTransformers(); err != nil { + return err + } + if err := c.tryLoadAlertSenders(); err != nil { + return err + } + } + return nil +} + +func (c *Config) GetConfigFile() string { return c.viper.GetString(configFile) } + +func (c *Config) GetFilters() []*FilterConfig { + if c.Filters == nil { + return nil + } + return c.Filters.filters +} + +func (c *Config) TryLoadFile(file string) error { + c.viper.SetConfigFile(file) + return c.viper.ReadInConfig() +} + +func (c *Config) validateConfig() error { + file := c.viper.GetString(configFile) + var out interface{} + b, err := os.ReadFile(file) + if err != nil { + return err + } + switch filepath.Ext(file) { + case ".yaml", ".yml": + err = yaml.Unmarshal(b, &out) + case ".json": + err = json.Unmarshal(b, &out) + default: + return fmt.Errorf("%s is not a supported config file extension", filepath.Ext(file)) + } + if err != nil { + return fmt.Errorf("couldn't read the config file: %v", err) + } + valid, errs := validate(configSchema, out) + if !valid || len(errs) > 0 { + return fmt.Errorf("invalid config: %v", multierror.Wrap(errs...)) + } + valid, errs = validate(configSchema, c.viper.AllSettings()) + if !valid || len(errs) > 0 { + return fmt.Errorf("invalid config: %v", multierror.Wrap(errs...)) + } + return nil +} + +func (c *Config) IsCaptureSet() bool { return c.CapFile != "" } +func (c *Config) IsFilamentSet() bool { return c.Filament.Name != "" } +func (c *Config) ConfigExists() bool { _, err := os.Stat(c.File()); return err == nil } +func (c *Config) File() string { return c.viper.GetString(configFile) } + +func (c *Config) addFlags() { + c.flags.String(configFile, defaultConfigFile(), "Indicates the location of the configuration file") + if c.opts.run { + c.flags.Bool(forwardMode, false, "Designates if event forwarding mode is engaged") + } + if c.opts.run || c.opts.replay || c.opts.validate { + c.flags.StringP(filamentName, "f", "", "Specifies the filament to execute") + c.flags.Bool(rulesEnabled, true, "Indicates if the rule engine is enabled and rules loaded") + c.flags.StringSlice(rulesFromPaths, defaultRulesPaths(), "Comma-separated list of rules files") + c.flags.StringSlice(macrosFromPaths, defaultMacrosPaths(), "Comma-separated list of macro files") + c.flags.StringSlice(rulesFromURLs, nil, "Comma-separated list of rules URL resources") + c.flags.Bool(matchAll, true, "Indicates if the match all strategy is enabled for the rule engine") + } + if c.opts.capture { + c.flags.StringP(capFile, "o", "", "The path of the output cap file") + } + if c.opts.replay { + c.flags.StringP(capFile, "k", "", "The path of the input cap file") + } + if c.opts.run || c.opts.replay || c.opts.list || c.opts.validate { + c.flags.String(filamentPath, defaultFilamentPath(), "Denotes the directory where filaments are located") + } + if c.opts.run || c.opts.replay || c.opts.capture || c.opts.stats { + c.flags.String(transport, "localhost:8080", "Specifies the underlying transport protocol for the API HTTP server") + c.flags.Duration(timeout, 15*time.Second, "Determines the timeout for the API server responses") + } + c.Log.AddFlags(c.flags) +} diff --git a/pkg/config/config.schema.json b/pkg/config/config.schema.json index e223db55c..a6ce003a9 100644 --- a/pkg/config/config.schema.json +++ b/pkg/config/config.schema.json @@ -335,6 +335,12 @@ "eventsource": { "type": "object", "properties": { + "enable-process": { + "type": "boolean" + }, + "enable-file": { + "type": "boolean" + }, "enable-thread": { "type": "boolean" }, @@ -395,6 +401,9 @@ "items": { "type": "string", "enum": [ + "execve", + "exit", + "clone", "CreateThread", "TerminateThread", "OpenProcess", diff --git a/pkg/config/config_linux.go b/pkg/config/config_linux.go index c00e1190c..7d803ce89 100644 --- a/pkg/config/config_linux.go +++ b/pkg/config/config_linux.go @@ -20,111 +20,27 @@ package config -import ( - "os" - "path/filepath" - "strings" +import "path/filepath" - "github.com/rabbitstack/fibratus/pkg/alertsender" - "github.com/rabbitstack/fibratus/pkg/util/log" - "github.com/spf13/cobra" - "github.com/spf13/pflag" - "github.com/spf13/viper" -) +type platformConfig struct{} -const configFile = "config-file" +func newPlatformConfig() platformConfig { return platformConfig{} } -type Config struct { - EventSource EventSourceConfig `json:"eventsource" yaml:"eventsource"` - Filament FilamentConfig `json:"filament" yaml:"filament"` - API APIConfig `json:"api" yaml:"api"` - Log log.Config `json:"logging" yaml:"logging"` - Filters *Filters `json:"filters" yaml:"filters"` - ForwardMode bool `json:"forward" yaml:"forward"` - CapFile string `json:"cap.file" yaml:"cap.file"` - Alertsenders []alertsender.Config `json:"-" yaml:"-"` - - flags *pflag.FlagSet - viper *viper.Viper - opts *Options -} - -type Options struct { - run bool - list bool - stats bool - validate bool -} - -type Option func(*Options) - -func WithRun() Option { return func(o *Options) { o.run = true } } -func WithList() Option { return func(o *Options) { o.list = true } } -func WithStats() Option { return func(o *Options) { o.stats = true } } -func WithValidate() Option { return func(o *Options) { o.validate = true } } - -func NewWithOpts(options ...Option) *Config { - opts := &Options{} - for _, option := range options { - option(opts) - } - v := viper.New() - v.AutomaticEnv() - v.SetEnvKeyReplacer(strings.NewReplacer("-", "_", ".", "_")) - c := &Config{ - Filters: &Filters{}, - flags: new(pflag.FlagSet), - viper: v, - opts: opts, - } - c.flags.String(configFile, filepath.Join("/etc", "fibratus", "fibratus.yml"), "Indicates the location of the configuration file") - c.flags.String(filamentName, "", "Specifies the filament to execute") - c.flags.String(filamentPath, "", "Denotes the directory where filaments are located") - c.flags.String(transport, "localhost:8080", "Specifies the underlying transport protocol for the API HTTP server") - c.flags.Bool(rulesEnabled, true, "Indicates if the rule engine is enabled and rules loaded") - c.flags.StringSlice(rulesFromPaths, nil, "Comma-separated list of rules files") - c.flags.StringSlice(macrosFromPaths, nil, "Comma-separated list of macro files") - c.flags.StringSlice(rulesFromURLs, nil, "Comma-separated list of rules URL resources") - c.flags.Bool(matchAll, true, "Indicates if the match all strategy is enabled") +func (c *Config) addPlatformFlags() { c.EventSource.AddFlags(c.flags) - c.Log.AddFlags(c.flags) - return c } -func (c *Config) MustViperize(cmd *cobra.Command) { - cmd.PersistentFlags().AddFlagSet(c.flags) - if err := c.viper.BindPFlags(cmd.PersistentFlags()); err != nil { - panic(err) - } -} +func (c *Config) initPlatform() {} -func (c *Config) Init() error { - c.EventSource.initFromViper(c.viper) - c.Filament.initFromViper(c.viper) - c.API.initFromViper(c.viper) - c.Log.InitFromViper(c.viper) - c.Filters.initFromViper(c.viper) - c.ForwardMode = c.viper.GetBool("forward") - c.CapFile = c.viper.GetString("cap.file") - if err := c.tryLoadAlertSenders(); err != nil && err != errNoAlertsendersSection { - return err - } - return nil -} +func (c *Config) Validate() error { return c.validateConfig() } -func (c *Config) GetConfigFile() string { return c.viper.GetString(configFile) } -func (c *Config) File() string { return c.GetConfigFile() } -func (c *Config) GetFilters() []*FilterConfig { - if c.Filters == nil { - return nil - } - return c.Filters.filters +func defaultConfigFile() string { return filepath.Join("/etc", "fibratus", "fibratus.yml") } +func defaultFilamentPath() string { + return filepath.Join("/usr", "share", "fibratus", "filaments") +} +func defaultRulesPaths() []string { + return []string{filepath.Join("/etc", "fibratus", "rules", "*")} } -func (c *Config) TryLoadFile(file string) error { - c.viper.SetConfigFile(file) - return c.viper.ReadInConfig() +func defaultMacrosPaths() []string { + return []string{filepath.Join("/etc", "fibratus", "rules", "macros", "*")} } -func (c *Config) Validate() error { return nil } -func (c *Config) IsCaptureSet() bool { return c.CapFile != "" } -func (c *Config) IsFilamentSet() bool { return c.Filament.Name != "" } -func (c *Config) ConfigExists() bool { _, err := os.Stat(c.File()); return err == nil } diff --git a/pkg/config/config_windows.go b/pkg/config/config_windows.go index ff5058100..9e7374d16 100644 --- a/pkg/config/config_windows.go +++ b/pkg/config/config_windows.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2019-2020 by Nedim Sabic Sabic * https://www.fibratus.io @@ -19,59 +21,25 @@ package config import ( - "encoding/json" - "fmt" - "time" - - "github.com/rabbitstack/fibratus/internal/evasion" - "golang.org/x/sys/windows" - - "github.com/rabbitstack/fibratus/pkg/outputs/eventlog" - - "github.com/rabbitstack/fibratus/pkg/outputs/http" - - "github.com/rabbitstack/fibratus/pkg/aggregator" - "github.com/rabbitstack/fibratus/pkg/aggregator/transformers" - removet "github.com/rabbitstack/fibratus/pkg/aggregator/transformers/remove" - replacet "github.com/rabbitstack/fibratus/pkg/aggregator/transformers/replace" - tagst "github.com/rabbitstack/fibratus/pkg/aggregator/transformers/tags" - "github.com/rabbitstack/fibratus/pkg/event" - "github.com/rabbitstack/fibratus/pkg/outputs/amqp" - "github.com/rabbitstack/fibratus/pkg/outputs/elasticsearch" - "github.com/rabbitstack/fibratus/pkg/util/log" - "github.com/rabbitstack/fibratus/pkg/util/multierror" - yara "github.com/rabbitstack/fibratus/pkg/yara/config" - "gopkg.in/yaml.v3" - - renamet "github.com/rabbitstack/fibratus/pkg/aggregator/transformers/rename" - trimt "github.com/rabbitstack/fibratus/pkg/aggregator/transformers/trim" - "os" "path/filepath" - "strings" - "github.com/rabbitstack/fibratus/pkg/alertsender" - eventlogsender "github.com/rabbitstack/fibratus/pkg/alertsender/eventlog" - mailsender "github.com/rabbitstack/fibratus/pkg/alertsender/mail" - slacksender "github.com/rabbitstack/fibratus/pkg/alertsender/slack" - systraysender "github.com/rabbitstack/fibratus/pkg/alertsender/systray" - "github.com/rabbitstack/fibratus/pkg/outputs" - "github.com/rabbitstack/fibratus/pkg/outputs/console" + "github.com/rabbitstack/fibratus/internal/evasion" + "github.com/rabbitstack/fibratus/pkg/alertsender/eventlog" + "github.com/rabbitstack/fibratus/pkg/alertsender/systray" + "github.com/rabbitstack/fibratus/pkg/event" + outputeventlog "github.com/rabbitstack/fibratus/pkg/outputs/eventlog" "github.com/rabbitstack/fibratus/pkg/pe" - "github.com/spf13/cobra" - "github.com/spf13/pflag" - "github.com/spf13/viper" + yara "github.com/rabbitstack/fibratus/pkg/yara/config" + "golang.org/x/sys/windows" ) const ( - capFile = "cap.file" - configFile = "config-file" debugPrivilege = "debug-privilege" initHandleSnapshot = "handle.init-snapshot" enumerateHandles = "handle.enumerate-handles" symbolPaths = "symbol-paths" symbolizeKernelAddresses = "symbolize-kernel-addresses" - forwardMode = "forward" serializeThreads = "event.serialize-threads" serializeModules = "event.serialize-modules" @@ -80,369 +48,99 @@ const ( serializeEnvs = "event.serialize-envs" ) -// Config stores configuration options for fine-tuning the behaviour of Fibratus. -type Config struct { - // EventSource stores different configuration options for fine-tuning the event source. - EventSource EventSourceConfig `json:"eventsource" yaml:"eventsource"` - // Filament contains filament settings - Filament FilamentConfig `json:"filament" yaml:"filament"` - // PE contains the settings that influences the behaviour of the PE (Portable Executable) reader. - PE pe.Config `json:"pe" yaml:"pe"` - // Output stores the currently active output config - Output outputs.Config - // InitHandleSnapshot indicates whether initial handle snapshot is built - InitHandleSnapshot bool `json:"init-handle-snapshot" yaml:"init-handle-snapshot"` - // EnumerateHandles indicates if process handles are collected during startup or - // when a new process is spawn - EnumerateHandles bool `json:"enumerate-handles" yaml:"enumerate-handles"` - // SymbolPaths designates the path or a series of paths separated by a semicolon - // that is used to search for symbols files. - SymbolPaths string `json:"symbol-paths" yaml:"symbols-paths"` - // SymbolizeKernelAddresses determines if kernel stack addresses are symbolized. - SymbolizeKernelAddresses bool `json:"symbolize-kernel-addresses" yaml:"symbolize-kernel-addresses"` - - // DebugPrivilege dictates if the SeDebugPrivilege is injected into - // Fibratus process' access token. - DebugPrivilege bool `json:"debug-privilege" yaml:"debug-privilege"` - // ForwardMode designates if event forwarding mode is engaged - ForwardMode bool `json:"forward" yaml:"forward"` - - // CapFile represents the name of the capture file. - CapFile string - - // API stores global HTTP API preferences - API APIConfig `json:"api" yaml:"api"` - // Yara contains configuration that influences the behaviour of the Yara engine - Yara yara.Config `json:"yara" yaml:"yara"` - // Aggregator stores event aggregator configuration - Aggregator aggregator.Config `json:"aggregator" yaml:"aggregator"` - // Log contains log-specific configuration options - Log log.Config `json:"logging" yaml:"logging"` - - // Transformers stores transformer configurations - Transformers []transformers.Config - // Alertsenders stores alert sender configurations - Alertsenders []alertsender.Config - - // Filters contains filter/rule definitions - Filters *Filters `json:"filters" yaml:"filters"` - - // Evasion controls the detection of evasion behaviours. - Evasion evasion.Config `json:"evasion" yaml:"evasion"` - - flags *pflag.FlagSet - viper *viper.Viper - opts *Options -} - -// Options determines which config flags are toggled depending on the command type. -type Options struct { - capture bool - replay bool - run bool - list bool - stats bool - validate bool +type platformConfig struct { + PE pe.Config `json:"pe" yaml:"pe"` + InitHandleSnapshot bool `json:"init-handle-snapshot" yaml:"init-handle-snapshot"` + EnumerateHandles bool `json:"enumerate-handles" yaml:"enumerate-handles"` + SymbolPaths string `json:"symbol-paths" yaml:"symbols-paths"` + SymbolizeKernelAddresses bool `json:"symbolize-kernel-addresses" yaml:"symbolize-kernel-addresses"` + DebugPrivilege bool `json:"debug-privilege" yaml:"debug-privilege"` + Yara yara.Config `json:"yara" yaml:"yara"` + Evasion evasion.Config `json:"evasion" yaml:"evasion"` } -// Option is the type alias for the config option. -type Option func(*Options) - -// WithCapture determines the capture command is executed. -func WithCapture() Option { - return func(o *Options) { - o.capture = true - } -} - -// WithReplay determines the replay command is executed. -func WithReplay() Option { - return func(o *Options) { - o.replay = true - } -} - -// WithRun determines the main command is executed. -func WithRun() Option { - return func(o *Options) { - o.run = true - } -} - -// WithList determines the list command is executed. -func WithList() Option { - return func(o *Options) { - o.list = true - } -} - -// WithStats determines the stats command is executed. -func WithStats() Option { - return func(o *Options) { - o.stats = true - } -} - -// WithValidate determines the validate command is executed. -func WithValidate() Option { - return func(o *Options) { - o.validate = true +func newPlatformConfig() platformConfig { + return platformConfig{ + PE: pe.Config{}, + Yara: yara.Config{}, } } -// NewWithOpts builds a new configuration store from a variety of sources such as configuration files, -// environment variables or command line flags. -func NewWithOpts(options ...Option) *Config { - opts := &Options{} - - for _, opt := range options { - opt(opts) - } - - v := viper.New() - v.AutomaticEnv() - v.SetEnvKeyReplacer(strings.NewReplacer("-", "_", ".", "_")) - - flagSet := new(pflag.FlagSet) - - c := &Config{ - EventSource: EventSourceConfig{}, - Filament: FilamentConfig{}, - API: APIConfig{}, - PE: pe.Config{}, - Log: log.Config{}, - Aggregator: aggregator.Config{}, - Filters: &Filters{}, - viper: v, - flags: flagSet, - opts: opts, - } - - if opts.run || opts.replay { - aggregator.AddFlags(flagSet) - console.AddFlags(flagSet) - amqp.AddFlags(flagSet) - elasticsearch.AddFlags(flagSet) - http.AddFlags(flagSet) - eventlog.AddFlags(flagSet) - removet.AddFlags(flagSet) - replacet.AddFlags(flagSet) - renamet.AddFlags(flagSet) - trimt.AddFlags(flagSet) - tagst.AddFlags(flagSet) - mailsender.AddFlags(flagSet) - slacksender.AddFlags(flagSet) - systraysender.AddFlags(flagSet) - eventlogsender.AddFlags(flagSet) - yara.AddFlags(flagSet) - } - - if opts.run || opts.capture { - pe.AddFlags(flagSet) - } - - if opts.run { - evasion.AddFlags(flagSet) +func (c *Config) addPlatformFlags() { + if c.opts.run || c.opts.replay { + outputeventlog.AddFlags(c.flags) + systray.AddFlags(c.flags) + eventlog.AddFlags(c.flags) + yara.AddFlags(c.flags) } - - c.addFlags() - - return c -} - -// GetConfigFile gets the path of the configuration file from Viper value. -func (c Config) GetConfigFile() string { - return c.viper.GetString(configFile) -} - -// GetFilters returns all rule filters loaded into the engine. -func (c Config) GetFilters() []*FilterConfig { - if c.Filters == nil { - return nil + if c.opts.run || c.opts.capture { + pe.AddFlags(c.flags) + c.EventSource.AddFlags(c.flags) } - return c.Filters.filters -} - -// MustViperize adds the flag set to the Cobra command and binds them within the Viper flags. -func (c *Config) MustViperize(cmd *cobra.Command) { - cmd.PersistentFlags().AddFlagSet(c.flags) - if err := c.viper.BindPFlags(cmd.PersistentFlags()); err != nil { - panic(err) + if c.opts.run { + evasion.AddFlags(c.flags) } - if c.opts.capture || c.opts.replay { - if err := cmd.MarkPersistentFlagRequired(capFile); err != nil { - panic(err) - } + if c.opts.run || c.opts.capture { + c.flags.Bool(initHandleSnapshot, false, "Indicates whether the initial handle snapshot is built") + c.flags.Bool(debugPrivilege, true, "Dictates if the SeDebugPrivilege is injected into the process token") + c.flags.Bool(enumerateHandles, false, "Indicates if process handles are collected") + c.flags.String(symbolPaths, "srv*c:\\\\SymCache*https://msdl.microsoft.com/download/symbols", "Designates paths used to search for symbol files") + c.flags.Bool(symbolizeKernelAddresses, false, "Determines if kernel stack addresses are symbolized") + c.flags.Bool(serializeThreads, false, "Indicates if threads are serialized as part of process state") + c.flags.Bool(serializeModules, false, "Indicates if modules are serialized as part of process state") + c.flags.Bool(serializeHandles, false, "Indicates if handles are serialized as part of process state") + c.flags.Bool(serializePE, false, "Indicates if PE metadata is serialized as part of process state") + c.flags.Bool(serializeEnvs, true, "Indicates if environment variables are serialized as part of process state") } } -// Init setups the configuration state from Viper. -func (c *Config) Init() error { - c.EventSource.initFromViper(c.viper) - c.Filament.initFromViper(c.viper) - c.API.initFromViper(c.viper) +func (c *Config) initPlatform() { c.PE.InitFromViper(c.viper) - c.Aggregator.InitFromViper(c.viper) - c.Log.InitFromViper(c.viper) c.Yara.InitFromViper(c.viper) - c.Filters.initFromViper(c.viper) - c.InitHandleSnapshot = c.viper.GetBool(initHandleSnapshot) c.EnumerateHandles = c.viper.GetBool(enumerateHandles) c.SymbolPaths = c.viper.GetString(symbolPaths) c.SymbolizeKernelAddresses = c.viper.GetBool(symbolizeKernelAddresses) c.DebugPrivilege = c.viper.GetBool(debugPrivilege) - c.ForwardMode = c.viper.GetBool(forwardMode) - c.CapFile = c.viper.GetString(capFile) - event.SerializeThreads = c.viper.GetBool(serializeThreads) event.SerializeModules = c.viper.GetBool(serializeModules) event.SerializeHandles = c.viper.GetBool(serializeHandles) event.SerializePE = c.viper.GetBool(serializePE) event.SerializeEnvs = c.viper.GetBool(serializeEnvs) - - if c.opts.run || c.opts.replay { - if err := c.tryLoadOutput(); err != nil { - return err - } - if err := c.tryLoadTransformers(); err != nil { - return err - } - if err := c.tryLoadAlertSenders(); err != nil { - return err - } - } - if c.opts.run { c.Evasion.InitFromViper(c.viper) } +} + +// Validate validates the configuration file and merged Viper settings against the schema. +func (c *Config) Validate() error { return c.validateConfig() } - return nil +func defaultConfigFile() string { + return filepath.Join(os.Getenv("PROGRAMFILES"), "fibratus", "config", "fibratus.yml") } -// IsCaptureSet determines if the events are stored -// in the capture file. -func (c *Config) IsCaptureSet() bool { return c.CapFile != "" } +func defaultFilamentPath() string { + return filepath.Join(os.Getenv("PROGRAMFILES"), "fibratus", "filaments") +} -// IsFilamentSet indicates if the filament is supplied. -func (c *Config) IsFilamentSet() bool { return c.Filament.Name != "" } +func defaultRulesPaths() []string { + return []string{filepath.Join(defaultRulesDir(), "*")} +} -// TryLoadFile attempts to load the configuration file from specified path on the file system. -func (c *Config) TryLoadFile(file string) error { - c.viper.SetConfigFile(file) - return c.viper.ReadInConfig() +func defaultMacrosPaths() []string { + return []string{filepath.Join(defaultRulesDir(), "Macros", "*")} } -// Validate ensures that all configuration options provided by user have the expected values. It returns -// a list of validation errors prefixed with the offending configuration property/flag. -func (c *Config) Validate() error { - // we'll first validate the structure and values of the config file - file := c.viper.GetString(configFile) - var out interface{} - b, err := os.ReadFile(file) - if err != nil { - return err - } - switch filepath.Ext(file) { - case ".yaml", ".yml": - err = yaml.Unmarshal(b, &out) - case ".json": - err = json.Unmarshal(b, &out) - default: - return fmt.Errorf("%s is not a supported config file extension", filepath.Ext(file)) - } +func defaultRulesDir() string { + exe, err := os.Executable() if err != nil { - return fmt.Errorf("couldn't read the config file: %v", err) - } - // validate config file content - valid, errs := validate(configSchema, out) - if !valid || len(errs) > 0 { - return fmt.Errorf("invalid config: %v", multierror.Wrap(errs...)) + exe = filepath.Join(os.Getenv("ProgramFiles"), "Fibratus", "Bin", "fibratus.exe") } - // now validate the Viper config flags - valid, errs = validate(configSchema, c.viper.AllSettings()) - if !valid || len(errs) > 0 { - return fmt.Errorf("invalid config: %v", multierror.Wrap(errs...)) - } - return nil + return filepath.Join(filepath.Dir(exe), "..", "Rules") } -// File returns the config file path. -func (c *Config) File() string { return c.viper.GetString(configFile) } - -// SymbolPathsUTF16 returns the symbol paths as UTF16 string -// suitable for use in the Debug Helper API functions. +// SymbolPathsUTF16 returns the symbol paths as a UTF-16 string. func (c *Config) SymbolPathsUTF16() *uint16 { paths, _ := windows.UTF16PtrFromString(c.SymbolPaths) return paths } - -func (c *Config) addFlags() { - c.flags.String(configFile, filepath.Join(os.Getenv("PROGRAMFILES"), "fibratus", "config", "fibratus.yml"), "Indicates the location of the configuration file") - if c.opts.run { - c.flags.Bool(forwardMode, false, "Designates if event forwarding mode is engaged") - } - if c.opts.run || c.opts.replay || c.opts.validate { - c.flags.StringP(filamentName, "f", "", "Specifies the filament to execute") - - // initialize default rules paths - exe, err := os.Executable() - if err != nil { - // fallback to default install directory - exe = filepath.Join(os.Getenv("ProgramFiles"), "Fibratus", "Bin", "fibratus.exe") - } - dir := filepath.Join(filepath.Dir(exe), "..", "Rules") - - c.flags.Bool(rulesEnabled, true, "Indicates if the rule engine is enabled and rules loaded") - c.flags.StringSlice(rulesFromPaths, []string{filepath.Join(dir, "*")}, "Comma-separated list of rules files") - c.flags.StringSlice(macrosFromPaths, []string{filepath.Join(dir, "Macros", "*")}, "Comma-separated list of macro files") - c.flags.StringSlice(rulesFromURLs, []string{}, "Comma-separated list of rules URL resources") - c.flags.Bool(matchAll, true, "Indicates if the match all strategy is enabled for the rule engine. If the match all strategy is enabled, a single event can trigger multiple rules") - } - if c.opts.capture { - c.flags.StringP(capFile, "o", "", "The path of the output cap file") - } - if c.opts.replay { - c.flags.StringP(capFile, "k", "", "The path of the input cap file") - } - if c.opts.run || c.opts.replay || c.opts.list || c.opts.validate { - c.flags.String(filamentPath, filepath.Join(os.Getenv("PROGRAMFILES"), "fibratus", "filaments"), "Denotes the directory where filaments are located") - } - if c.opts.run || c.opts.replay || c.opts.capture || c.opts.stats { - c.flags.String(transport, `localhost:8080`, "Specifies the underlying transport protocol for the API HTTP server") - c.flags.Duration(timeout, time.Second*15, "Determines the timeout for the API server responses") - } - if c.opts.run || c.opts.capture { - c.flags.Bool(initHandleSnapshot, false, "Indicates whether initial handle snapshot is built. This implies scanning the system handles table and producing an entry for each handle object") - c.flags.Bool(debugPrivilege, true, "Dictates if the SeDebugPrivilege is injected into Fibratus process' access token") - c.flags.Bool(enumerateHandles, false, "Indicates if process handles are collected during startup or when a new process is spawn") - c.flags.String(symbolPaths, "srv*c:\\\\SymCache*https://msdl.microsoft.com/download/symbols", "Designates the path or a series of paths separated by a semicolon that is used to search for symbols files") - c.flags.Bool(symbolizeKernelAddresses, false, "Determines if kernel stack addresses are symbolized") - - c.flags.Bool(enableThreadEvents, true, "Determines whether thread events are collected by Kernel Logger provider") - c.flags.Bool(enableRegistryEvents, true, "Determines whether registry events are collected by Kernel Logger provider") - c.flags.Bool(enableNetEvents, true, "Determines whether network (TCP/UDP) events are collected by Kernel Logger provider") - c.flags.Bool(enableFileIOEvents, true, "Determines whether disk I/O events are collected by Kernel Logger provider") - c.flags.Bool(enableVAMapEvents, true, "Determines whether VA map/unmap events are collected by Kernel Logger provider") - c.flags.Bool(enableModuleEvents, true, "Determines whether module events are collected by Kernel Logger provider") - c.flags.Bool(enableHandleEvents, false, "Determines whether object manager events (handle creation/destruction) are collected by Kernel Logger provider") - c.flags.Bool(enableMemEvents, true, "Determines whether memory manager events are collected by Kernel Logger provider") - c.flags.Bool(enableAuditAPIEvents, true, "Determines whether kernel audit API calls events are published") - c.flags.Bool(enableDNSEvents, true, "Determines whether DNS client events are enabled") - c.flags.Bool(enableThreadpoolEvents, true, "Determines whether thread pool events are published") - c.flags.Bool(stackEnrichment, true, "Indicates if stack enrichment is enabled for eligible events") - c.flags.Int(bufferSize, int(maxBufferSize), "Represents the amount of memory allocated for each event tracing session buffer, in kilobytes. The buffer size affects the rate at which buffers fill and must be flushed (small buffer size requires less memory but it increases the rate at which buffers must be flushed)") - c.flags.Int(minBuffers, int(defaultMinBuffers), "Determines the minimum number of buffers allocated for the event tracing session's buffer pool") - c.flags.Int(maxBuffers, int(defaultMaxBuffers), "Determines the maximum number of buffers allocated for the event tracing session's buffer pool") - c.flags.Duration(flushInterval, defaultFlushInterval, "Specifies how often the trace buffers are forcibly flushed") - c.flags.StringSlice(excludedEvents, []string{}, "A list of symbolical kernel event names that will be dropped from the event stream. By default all events are accepted") - c.flags.StringSlice(excludedImages, []string{}, "A list of image names that will be dropped from the event stream. Image names are case sensitive") - - c.flags.Bool(serializeThreads, false, "Indicates if threads are serialized as part of the process state") - c.flags.Bool(serializeModules, false, "Indicates if modules are serialized as part of the process state") - c.flags.Bool(serializeHandles, false, "Indicates if handles are serialized as part of the process state") - c.flags.Bool(serializePE, false, "Indicates if the PE metadata are serialized as part of the process state") - c.flags.Bool(serializeEnvs, true, "Indicates if environment variables are serialized as part of the process state") - } - c.Log.AddFlags(c.flags) -} diff --git a/pkg/config/eventsource.go b/pkg/config/eventsource.go index 5cfbf1b92..63e097d2c 100644 --- a/pkg/config/eventsource.go +++ b/pkg/config/eventsource.go @@ -1,8 +1,6 @@ -//go:build windows -// +build windows - /* * Copyright 2019-2020 by Nedim Sabic Sabic + * Copyright 2026 by Mostafa Moradian * https://www.fibratus.io * All Rights Reserved. * @@ -22,195 +20,61 @@ package config import ( - "runtime" - "time" - "github.com/rabbitstack/fibratus/pkg/event" - "github.com/rabbitstack/fibratus/pkg/util/bitmask" - pstypes "github.com/rabbitstack/fibratus/pkg/ps/types" - "github.com/spf13/viper" -) - -const ( - enableThreadEvents = "eventsource.enable-thread" - enableRegistryEvents = "eventsource.enable-registry" - enableNetEvents = "eventsource.enable-net" - enableFileIOEvents = "eventsource.enable-fileio" - enableVAMapEvents = "eventsource.enable-vamap" - enableModuleEvents = "eventsource.enable-module" - enableHandleEvents = "eventsource.enable-handle" - enableMemEvents = "eventsource.enable-mem" - enableAuditAPIEvents = "eventsource.enable-audit-api" - enableDNSEvents = "eventsource.enable-dns" - enableThreadpoolEvents = "eventsource.enable-threadpool" - stackEnrichment = "eventsource.stack-enrichment" - bufferSize = "eventsource.buffer-size" - minBuffers = "eventsource.min-buffers" - maxBuffers = "eventsource.max-buffers" - flushInterval = "eventsource.flush-interval" - - excludedEvents = "eventsource.blacklist.events" - excludedImages = "eventsource.blacklist.images" - - maxBufferSize = uint32(512) -) - -var ( - defaultMinBuffers = uint32(runtime.NumCPU() * 2) - defaultMaxBuffers = uint32(runtime.NumCPU() * 8) - defaultFlushInterval = time.Second + "github.com/rabbitstack/fibratus/pkg/util/bitmask" ) -// EventSourceConfig stores different configuration options for fine-tuning the event source. -type EventSourceConfig struct { - // EnableThreadEvents indicates if thread events are collected by the ETW provider. - EnableThreadEvents bool `json:"enable-thread" yaml:"enable-thread"` - // EnableRegistryEvents indicates if registry events are collected by the ETW provider. - EnableRegistryEvents bool `json:"enable-registry" yaml:"enable-registry"` - // EnableNetEvents determines whether network (TCP/UDP) events are collected by the ETW provider. - EnableNetEvents bool `json:"enable-net" yaml:"enable-net"` - // EnableFileIOEvents indicates if file I/O events are collected by the ETW provider. - EnableFileIOEvents bool `json:"enable-fileio" yaml:"enable-fileio"` - // EnableVAMapEvents indicates if VA map/unmap events are collected by the ETW provider. - EnableVAMapEvents bool `json:"enable-vamap" yaml:"enable-vamap"` - // EnableModuleEvents indicates if module events are collected by the ETW provider. - EnableModuleEvents bool `json:"enable-image" yaml:"enable-module"` - // EnableHandleEvents indicates whether handle creation/disposal events are enabled. - EnableHandleEvents bool `json:"enable-handle" yaml:"enable-handle"` - // EnableMemEvents indicates whether memory manager events are enabled. - EnableMemEvents bool `json:"enable-memory" yaml:"enable-memory"` - // EnableAuditAPIEvents indicates if kernel audit API calls events are enabled - EnableAuditAPIEvents bool `json:"enable-audit-api" yaml:"enable-audit-api"` - // EnableDNSEvents indicates if DNS client events are enabled - EnableDNSEvents bool `json:"enable-dns" yaml:"enable-dns"` - // EnableThreadpoolEvents indicates if thread pool events are enabled - EnableThreadpoolEvents bool `json:"enable-threadpool" yaml:"enable-threadpool"` - // StackEnrichment indicates if stack enrichment is enabled for eligible events. - StackEnrichment bool `json:"stack-enrichment" yaml:"stack-enrichment"` - // BufferSize represents the amount of memory allocated for each event tracing session buffer, in kilobytes. - // The buffer size affects the rate at which buffers fill and must be flushed (small buffer size requires - // less memory, but it increases the rate at which buffers must be flushed). - BufferSize uint32 `json:"buffer-size" yaml:"buffer-size"` - // MinBuffers determines the minimum number of buffers allocated for the event tracing session's buffer pool. - MinBuffers uint32 `json:"min-buffers" yaml:"min-buffers"` - // MaxBuffers is the maximum number of buffers allocated for the event tracing session's buffer pool. - MaxBuffers uint32 `json:"max-buffers" yaml:"max-buffers"` - // FlushTimer specifies how often the trace buffers are forcibly flushed. - FlushTimer time.Duration `json:"flush-interval" yaml:"flush-interval"` - // ExcludedEvents are kernel event names that will be dropped from the kernel event stream. - ExcludedEvents []string `json:"blacklist.events" yaml:"blacklist.events"` - // ExcludedImages are process image names that will be rejected if they generate a kernel event. - ExcludedImages []string `json:"blacklist.images" yaml:"blacklist.images"` - - dropMasks *bitmask.Bitmask - allMasks *bitmask.Bitmask - +type eventSourceConfig struct { + dropMasks *bitmask.Bitmask + allMasks *bitmask.Bitmask excludedImages map[string]bool } -func (c *EventSourceConfig) initFromViper(v *viper.Viper) { - c.EnableThreadEvents = v.GetBool(enableThreadEvents) - c.EnableRegistryEvents = v.GetBool(enableRegistryEvents) - c.EnableNetEvents = v.GetBool(enableNetEvents) - c.EnableFileIOEvents = v.GetBool(enableFileIOEvents) - c.EnableVAMapEvents = v.GetBool(enableVAMapEvents) - c.EnableModuleEvents = v.GetBool(enableModuleEvents) - c.EnableHandleEvents = v.GetBool(enableHandleEvents) - c.EnableMemEvents = v.GetBool(enableMemEvents) - c.EnableAuditAPIEvents = v.GetBool(enableAuditAPIEvents) - c.EnableDNSEvents = v.GetBool(enableDNSEvents) - c.EnableThreadpoolEvents = v.GetBool(enableThreadpoolEvents) - c.StackEnrichment = v.GetBool(stackEnrichment) - c.BufferSize = uint32(v.GetInt(bufferSize)) - c.MinBuffers = uint32(v.GetInt(minBuffers)) - c.MaxBuffers = uint32(v.GetInt(maxBuffers)) - c.FlushTimer = v.GetDuration(flushInterval) - c.ExcludedEvents = v.GetStringSlice(excludedEvents) - c.ExcludedImages = v.GetStringSlice(excludedImages) - +func (c *EventSourceConfig) initEventMasks(types []event.Type) { c.dropMasks = bitmask.New() c.allMasks = bitmask.New() - c.excludedImages = make(map[string]bool) for _, name := range c.ExcludedEvents { - if typ := event.NameToType(name); typ != event.UnknownType { - c.dropMasks.Set(typ.ID()) + for _, typ := range event.NameToTypes(name) { + if typ != event.UnknownType { + c.dropMasks.Set(typ.ID()) + } } } - - for _, typ := range event.AllWithState() { + for _, typ := range types { c.allMasks.Set(typ.ID()) } - for _, name := range c.ExcludedImages { c.excludedImages[name] = true } } -// Init is an exported method to allow initializing exclusion maps from external modules. +// Init initializes event and image exclusion maps. func (c *EventSourceConfig) Init() { - c.excludedImages = make(map[string]bool) + c.initEventMasks(platformEventTypes()) +} +func (c *EventSourceConfig) SetDropMask(typ event.Type) { if c.dropMasks == nil { c.dropMasks = bitmask.New() } - for _, name := range c.ExcludedEvents { - for _, typ := range event.NameToTypes(name) { - if typ != event.UnknownType { - c.dropMasks.Set(typ.ID()) - } - } - } - - for _, name := range c.ExcludedImages { - c.excludedImages[name] = true - } - - if c.allMasks == nil { - c.allMasks = bitmask.New() - } - for _, typ := range event.AllWithState() { - c.allMasks.Set(typ.ID()) - } -} - -// SetDropMask inserts the event mask in the bitset to -// instruct the given event type should be dropped from -// the event stream. -func (c *EventSourceConfig) SetDropMask(typ event.Type) { c.dropMasks.Set(typ.ID()) } -// TestDropMask checks if the specified event type has -// the drop mask in the bitset. func (c *EventSourceConfig) TestDropMask(typ event.Type) bool { - return c.dropMasks.IsSet(typ.ID()) + return c.dropMasks != nil && c.dropMasks.IsSet(typ.ID()) } -// ExcludeEvent determines whether the supplied short -// event ID exists in the bitset of excluded events. func (c *EventSourceConfig) ExcludeEvent(id uint) bool { - return c.dropMasks.IsSet(id) + return c.dropMasks != nil && c.dropMasks.IsSet(id) } -// EventExists determines if the provided event ID exists -// in the internal event catalog by checking the event ID -// bitmask. func (c *EventSourceConfig) EventExists(id uint) bool { - return c.allMasks.IsSet(id) + return c.allMasks != nil && c.allMasks.IsSet(id) } -// ExcludeImage determines whether the process generating event is present in the -// list of excluded images. If the hit occurs, the event associated with the process -// is dropped. func (c *EventSourceConfig) ExcludeImage(ps *pstypes.PS) bool { - if len(c.excludedImages) == 0 { - return false - } - if ps == nil { - return false - } - return c.excludedImages[ps.Name] + return ps != nil && c.excludedImages[ps.Name] } diff --git a/pkg/config/eventsource_linux.go b/pkg/config/eventsource_linux.go index 68b2f12a7..7de7ba2c1 100644 --- a/pkg/config/eventsource_linux.go +++ b/pkg/config/eventsource_linux.go @@ -22,8 +22,6 @@ package config import ( "github.com/rabbitstack/fibratus/pkg/event" - pstypes "github.com/rabbitstack/fibratus/pkg/ps/types" - "github.com/rabbitstack/fibratus/pkg/util/bitmask" "github.com/spf13/pflag" "github.com/spf13/viper" ) @@ -38,16 +36,14 @@ const ( ) type EventSourceConfig struct { + eventSourceConfig + + ExcludedEvents []string `json:"blacklist.events" yaml:"blacklist.events"` + ExcludedImages []string `json:"blacklist.images" yaml:"blacklist.images"` EnableProcessEvents bool `json:"enable-process" yaml:"enable-process"` EnableFileIOEvents bool `json:"enable-file" yaml:"enable-file"` EnableNetEvents bool `json:"enable-net" yaml:"enable-net"` EnableMemEvents bool `json:"enable-mem" yaml:"enable-mem"` - ExcludedEvents []string `json:"blacklist.events" yaml:"blacklist.events"` - ExcludedImages []string `json:"blacklist.images" yaml:"blacklist.images"` - - dropMasks *bitmask.Bitmask - allMasks *bitmask.Bitmask - excludedImages map[string]bool } func (c *EventSourceConfig) AddFlags(flags *pflag.FlagSet) { @@ -69,33 +65,4 @@ func (c *EventSourceConfig) initFromViper(v *viper.Viper) { c.Init() } -func (c *EventSourceConfig) Init() { - c.dropMasks = bitmask.New() - c.allMasks = bitmask.New() - c.excludedImages = make(map[string]bool) - for _, name := range c.ExcludedEvents { - for _, typ := range event.NameToTypes(name) { - c.dropMasks.Set(typ.ID()) - } - } - for _, typ := range event.AllWithState() { - c.allMasks.Set(typ.ID()) - } - for _, name := range c.ExcludedImages { - c.excludedImages[name] = true - } -} - -func (c *EventSourceConfig) SetDropMask(typ event.Type) { c.dropMasks.Set(typ.ID()) } -func (c *EventSourceConfig) TestDropMask(typ event.Type) bool { - return c.dropMasks != nil && c.dropMasks.IsSet(typ.ID()) -} -func (c *EventSourceConfig) ExcludeEvent(id uint) bool { - return c.dropMasks != nil && c.dropMasks.IsSet(id) -} -func (c *EventSourceConfig) EventExists(id uint) bool { - return c.allMasks != nil && c.allMasks.IsSet(id) -} -func (c *EventSourceConfig) ExcludeImage(ps *pstypes.PS) bool { - return ps != nil && c.excludedImages[ps.Name] -} +func platformEventTypes() []event.Type { return event.All() } diff --git a/pkg/config/eventsource_linux_test.go b/pkg/config/eventsource_linux_test.go new file mode 100644 index 000000000..140fdc91a --- /dev/null +++ b/pkg/config/eventsource_linux_test.go @@ -0,0 +1,71 @@ +//go:build linux + +/* + * Copyright 2026 by Mostafa Moradian + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package config + +import ( + "os" + "path/filepath" + "testing" + + "github.com/rabbitstack/fibratus/pkg/event" + pstypes "github.com/rabbitstack/fibratus/pkg/ps/types" + "github.com/stretchr/testify/require" +) + +func TestEventSourceConfigLinux(t *testing.T) { + c := NewWithOpts(WithRun()) + require.NoError(t, c.flags.Parse([]string{ + "--eventsource.enable-process=false", + "--eventsource.blacklist.events=execve", + "--eventsource.blacklist.images=systemd", + })) + require.NoError(t, c.viper.BindPFlags(c.flags)) + require.NoError(t, c.Init()) + + require.False(t, c.EventSource.EnableProcessEvents) + require.True(t, c.EventSource.ExcludeEvent(event.Execve.ID())) + require.True(t, c.EventSource.ExcludeImage(&pstypes.PS{Name: "systemd"})) + for _, typ := range event.All() { + require.True(t, c.EventSource.EventExists(typ.ID())) + } +} + +func TestValidateLinuxEventSource(t *testing.T) { + file := filepath.Join(t.TempDir(), "fibratus.yml") + require.NoError(t, os.WriteFile(file, []byte(`eventsource: + enable-process: true + enable-file: true + blacklist: + events: + - execve + - exit + - clone + images: + - systemd +`), 0o600)) + + c := NewWithOpts(WithRun()) + require.NoError(t, c.flags.Parse([]string{"--config-file=" + file})) + require.NoError(t, c.viper.BindPFlags(c.flags)) + require.NoError(t, c.TryLoadFile(c.GetConfigFile())) + require.NoError(t, c.Init()) + require.NoError(t, c.Validate()) +} diff --git a/pkg/config/eventsource_windows.go b/pkg/config/eventsource_windows.go new file mode 100644 index 000000000..499724bdd --- /dev/null +++ b/pkg/config/eventsource_windows.go @@ -0,0 +1,126 @@ +//go:build windows + +/* + * Copyright 2019-2020 by Nedim Sabic Sabic + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package config + +import ( + "runtime" + "time" + + "github.com/rabbitstack/fibratus/pkg/event" + "github.com/spf13/pflag" + "github.com/spf13/viper" +) + +const ( + enableThreadEvents = "eventsource.enable-thread" + enableRegistryEvents = "eventsource.enable-registry" + enableNetEvents = "eventsource.enable-net" + enableFileIOEvents = "eventsource.enable-fileio" + enableVAMapEvents = "eventsource.enable-vamap" + enableModuleEvents = "eventsource.enable-module" + enableHandleEvents = "eventsource.enable-handle" + enableMemEvents = "eventsource.enable-mem" + enableAuditAPIEvents = "eventsource.enable-audit-api" + enableDNSEvents = "eventsource.enable-dns" + enableThreadpoolEvents = "eventsource.enable-threadpool" + stackEnrichment = "eventsource.stack-enrichment" + bufferSize = "eventsource.buffer-size" + minBuffers = "eventsource.min-buffers" + maxBuffers = "eventsource.max-buffers" + flushInterval = "eventsource.flush-interval" + excludedEvents = "eventsource.blacklist.events" + excludedImages = "eventsource.blacklist.images" + maxBufferSize = uint32(512) +) + +var ( + defaultMinBuffers = uint32(runtime.NumCPU() * 2) + defaultMaxBuffers = uint32(runtime.NumCPU() * 8) + defaultFlushInterval = time.Second +) + +type EventSourceConfig struct { + eventSourceConfig + + ExcludedEvents []string `json:"blacklist.events" yaml:"blacklist.events"` + ExcludedImages []string `json:"blacklist.images" yaml:"blacklist.images"` + EnableThreadEvents bool `json:"enable-thread" yaml:"enable-thread"` + EnableRegistryEvents bool `json:"enable-registry" yaml:"enable-registry"` + EnableNetEvents bool `json:"enable-net" yaml:"enable-net"` + EnableFileIOEvents bool `json:"enable-fileio" yaml:"enable-fileio"` + EnableVAMapEvents bool `json:"enable-vamap" yaml:"enable-vamap"` + EnableModuleEvents bool `json:"enable-image" yaml:"enable-module"` + EnableHandleEvents bool `json:"enable-handle" yaml:"enable-handle"` + EnableMemEvents bool `json:"enable-memory" yaml:"enable-memory"` + EnableAuditAPIEvents bool `json:"enable-audit-api" yaml:"enable-audit-api"` + EnableDNSEvents bool `json:"enable-dns" yaml:"enable-dns"` + EnableThreadpoolEvents bool `json:"enable-threadpool" yaml:"enable-threadpool"` + StackEnrichment bool `json:"stack-enrichment" yaml:"stack-enrichment"` + BufferSize uint32 `json:"buffer-size" yaml:"buffer-size"` + MinBuffers uint32 `json:"min-buffers" yaml:"min-buffers"` + MaxBuffers uint32 `json:"max-buffers" yaml:"max-buffers"` + FlushTimer time.Duration `json:"flush-interval" yaml:"flush-interval"` +} + +func (c *EventSourceConfig) AddFlags(flags *pflag.FlagSet) { + flags.Bool(enableThreadEvents, true, "Determines whether thread events are collected") + flags.Bool(enableRegistryEvents, true, "Determines whether registry events are collected") + flags.Bool(enableNetEvents, true, "Determines whether network events are collected") + flags.Bool(enableFileIOEvents, true, "Determines whether file I/O events are collected") + flags.Bool(enableVAMapEvents, true, "Determines whether VA map/unmap events are collected") + flags.Bool(enableModuleEvents, true, "Determines whether module events are collected") + flags.Bool(enableHandleEvents, false, "Determines whether handle events are collected") + flags.Bool(enableMemEvents, true, "Determines whether memory events are collected") + flags.Bool(enableAuditAPIEvents, true, "Determines whether audit API events are collected") + flags.Bool(enableDNSEvents, true, "Determines whether DNS events are collected") + flags.Bool(enableThreadpoolEvents, true, "Determines whether thread pool events are collected") + flags.Bool(stackEnrichment, true, "Indicates if stack enrichment is enabled") + flags.Int(bufferSize, int(maxBufferSize), "Represents the trace buffer size in kilobytes") + flags.Int(minBuffers, int(defaultMinBuffers), "Determines the minimum trace buffer count") + flags.Int(maxBuffers, int(defaultMaxBuffers), "Determines the maximum trace buffer count") + flags.Duration(flushInterval, defaultFlushInterval, "Specifies how often trace buffers are flushed") + flags.StringSlice(excludedEvents, nil, "A list of event names to drop") + flags.StringSlice(excludedImages, nil, "A list of image names to drop") +} + +func (c *EventSourceConfig) initFromViper(v *viper.Viper) { + c.EnableThreadEvents = v.GetBool(enableThreadEvents) + c.EnableRegistryEvents = v.GetBool(enableRegistryEvents) + c.EnableNetEvents = v.GetBool(enableNetEvents) + c.EnableFileIOEvents = v.GetBool(enableFileIOEvents) + c.EnableVAMapEvents = v.GetBool(enableVAMapEvents) + c.EnableModuleEvents = v.GetBool(enableModuleEvents) + c.EnableHandleEvents = v.GetBool(enableHandleEvents) + c.EnableMemEvents = v.GetBool(enableMemEvents) + c.EnableAuditAPIEvents = v.GetBool(enableAuditAPIEvents) + c.EnableDNSEvents = v.GetBool(enableDNSEvents) + c.EnableThreadpoolEvents = v.GetBool(enableThreadpoolEvents) + c.StackEnrichment = v.GetBool(stackEnrichment) + c.BufferSize = uint32(v.GetInt(bufferSize)) + c.MinBuffers = uint32(v.GetInt(minBuffers)) + c.MaxBuffers = uint32(v.GetInt(maxBuffers)) + c.FlushTimer = v.GetDuration(flushInterval) + c.ExcludedEvents = v.GetStringSlice(excludedEvents) + c.ExcludedImages = v.GetStringSlice(excludedImages) + c.Init() +} + +func platformEventTypes() []event.Type { return event.AllWithState() } diff --git a/pkg/config/output.go b/pkg/config/output.go index d3a88fe91..a91d4e234 100644 --- a/pkg/config/output.go +++ b/pkg/config/output.go @@ -1,5 +1,3 @@ -//go:build windows - /* * Copyright 2019-2020 by Nedim Sabic Sabic * https://www.fibratus.io @@ -26,8 +24,6 @@ import ( "reflect" "strconv" - "github.com/rabbitstack/fibratus/pkg/outputs/eventlog" - "github.com/rabbitstack/fibratus/pkg/outputs" "github.com/rabbitstack/fibratus/pkg/outputs/amqp" "github.com/rabbitstack/fibratus/pkg/outputs/console" @@ -35,7 +31,6 @@ import ( "github.com/rabbitstack/fibratus/pkg/outputs/http" "github.com/rabbitstack/fibratus/pkg/outputs/null" log "github.com/sirupsen/logrus" - "golang.org/x/sys/windows/svc" ) var errNoOutputSection = errors.New("no output section in config") @@ -118,27 +113,15 @@ func (c *Config) tryLoadOutput() error { } c.Output.Type, c.Output.Output = outputs.HTTP, httpConfig - case outputs.Eventlog: - var eventlogConfig eventlog.Config - if err := decode(config, &eventlogConfig); err != nil { - return errOutputConfig(typ, err) - } - if !eventlogConfig.Enabled { - continue + default: + if err := c.loadPlatformOutput(outputs.TypeFromString(typ), typ, config); err != nil { + return err } - c.Output.Type, c.Output.Output = outputs.Eventlog, eventlogConfig } } - // if it is not an interactive session but the console output is enabled - // we default to null output and warn about that - if isWindowsService() && c.Output.Output != nil { - if c.Output.Type == outputs.Console { - log.Warn("running in non-interactive session with console output. " + - "Please configure a different output type. Defaulting to null output") - c.Output.Type, c.Output.Output = outputs.Null, &null.Config{} - return nil - } + if c.adjustPlatformOutput() { + return nil } // default to null output @@ -160,12 +143,3 @@ func findActiveOutputs(outputs map[string]interface{}) []string { } return outputTypes } - -// isWindowsService returns true if the process is running inside Windows Service. -func isWindowsService() bool { - isWinService, err := svc.IsWindowsService() - if err != nil { - return false - } - return isWinService -} diff --git a/pkg/config/schema_linux.go b/pkg/config/output_linux.go similarity index 73% rename from pkg/config/schema_linux.go rename to pkg/config/output_linux.go index 136a9a4ae..85cd3833b 100644 --- a/pkg/config/schema_linux.go +++ b/pkg/config/output_linux.go @@ -20,13 +20,7 @@ package config -import _ "embed" +import "github.com/rabbitstack/fibratus/pkg/outputs" -//go:embed config.schema.json -var configSchema string - -//go:embed rules.schema.json -var rulesSchema string - -//go:embed macros.schema.json -var macrosSchema string +func (c *Config) loadPlatformOutput(_ outputs.Type, _ string, _ interface{}) error { return nil } +func (c *Config) adjustPlatformOutput() bool { return false } diff --git a/pkg/config/output_linux_test.go b/pkg/config/output_linux_test.go new file mode 100644 index 000000000..a6055c2d3 --- /dev/null +++ b/pkg/config/output_linux_test.go @@ -0,0 +1,38 @@ +//go:build linux + +/* + * Copyright 2026 by Mostafa Moradian + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package config + +import ( + "testing" + + "github.com/rabbitstack/fibratus/pkg/outputs/null" + "github.com/stretchr/testify/require" +) + +func TestEventlogOutputDefaultsToNull(t *testing.T) { + c := NewWithOpts(WithRun()) + require.NoError(t, c.flags.Parse([]string{"--config-file=_fixtures/eventlog-output.yml"})) + require.NoError(t, c.viper.BindPFlags(c.flags)) + require.NoError(t, c.TryLoadFile(c.GetConfigFile())) + require.NoError(t, c.Init()) + + require.IsType(t, &null.Config{}, c.Output.Output) +} diff --git a/pkg/config/output_test.go b/pkg/config/output_test.go index 7aa60a487..cc221014d 100644 --- a/pkg/config/output_test.go +++ b/pkg/config/output_test.go @@ -1,5 +1,3 @@ -//go:build windows - /* * Copyright 2019-2020 by Nedim Sabic Sabic * https://www.fibratus.io @@ -24,8 +22,6 @@ import ( "testing" "time" - "github.com/rabbitstack/fibratus/pkg/outputs/eventlog" - "github.com/rabbitstack/fibratus/pkg/outputs/amqp" "github.com/rabbitstack/fibratus/pkg/outputs/http" "github.com/stretchr/testify/assert" @@ -81,21 +77,3 @@ func TestHTTPOutput(t *testing.T) { assert.Len(t, httpConfig.Headers, 2) assert.Equal(t, "kkvvkk", httpConfig.Headers["api-key"]) } - -func TestEventlogOutput(t *testing.T) { - c := NewWithOpts(WithRun()) - - err := c.flags.Parse([]string{"--config-file=_fixtures/eventlog-output.yml"}) - require.NoError(t, c.viper.BindPFlags(c.flags)) - require.NoError(t, err) - require.NoError(t, c.TryLoadFile(c.GetConfigFile())) - - require.NoError(t, c.Init()) - - require.NotNil(t, c.Output) - require.IsType(t, eventlog.Config{}, c.Output.Output) - - eventlogConfig := c.Output.Output.(eventlog.Config) - assert.True(t, eventlogConfig.Enabled) - assert.Equal(t, "INFO", eventlogConfig.Level) -} diff --git a/pkg/config/output_windows.go b/pkg/config/output_windows.go new file mode 100644 index 000000000..1e2a8b850 --- /dev/null +++ b/pkg/config/output_windows.go @@ -0,0 +1,58 @@ +//go:build windows + +/* + * Copyright 2019-2020 by Nedim Sabic Sabic + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package config + +import ( + "github.com/rabbitstack/fibratus/pkg/outputs" + "github.com/rabbitstack/fibratus/pkg/outputs/eventlog" + "github.com/rabbitstack/fibratus/pkg/outputs/null" + log "github.com/sirupsen/logrus" + "golang.org/x/sys/windows/svc" +) + +func (c *Config) loadPlatformOutput(output outputs.Type, typ string, config interface{}) error { + if output != outputs.Eventlog { + return nil + } + var eventlogConfig eventlog.Config + if err := decode(config, &eventlogConfig); err != nil { + return errOutputConfig(typ, err) + } + if eventlogConfig.Enabled { + c.Output.Type, c.Output.Output = outputs.Eventlog, eventlogConfig + } + return nil +} + +func (c *Config) adjustPlatformOutput() bool { + if !isWindowsService() || c.Output.Type != outputs.Console || c.Output.Output == nil { + return false + } + log.Warn("running in non-interactive session with console output. " + + "Please configure a different output type. Defaulting to null output") + c.Output.Type, c.Output.Output = outputs.Null, &null.Config{} + return true +} + +func isWindowsService() bool { + isWinService, err := svc.IsWindowsService() + return err == nil && isWinService +} diff --git a/pkg/config/output_windows_test.go b/pkg/config/output_windows_test.go new file mode 100644 index 000000000..c6ab53816 --- /dev/null +++ b/pkg/config/output_windows_test.go @@ -0,0 +1,41 @@ +//go:build windows + +/* + * Copyright 2019-2020 by Nedim Sabic Sabic + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package config + +import ( + "testing" + + "github.com/rabbitstack/fibratus/pkg/outputs/eventlog" + "github.com/stretchr/testify/require" +) + +func TestEventlogOutput(t *testing.T) { + c := NewWithOpts(WithRun()) + require.NoError(t, c.flags.Parse([]string{"--config-file=_fixtures/eventlog-output.yml"})) + require.NoError(t, c.viper.BindPFlags(c.flags)) + require.NoError(t, c.TryLoadFile(c.GetConfigFile())) + require.NoError(t, c.Init()) + + require.IsType(t, eventlog.Config{}, c.Output.Output) + eventlogConfig := c.Output.Output.(eventlog.Config) + require.True(t, eventlogConfig.Enabled) + require.Equal(t, "INFO", eventlogConfig.Level) +} diff --git a/pkg/config/print_test.go b/pkg/config/print_test.go index 036226c86..beea1c593 100644 --- a/pkg/config/print_test.go +++ b/pkg/config/print_test.go @@ -1,5 +1,3 @@ -//go:build windows - /* * Copyright 2019-2020 by Nedim Sabic Sabic * https://www.fibratus.io @@ -21,13 +19,14 @@ package config import ( - "github.com/stretchr/testify/require" "testing" + + "github.com/stretchr/testify/require" ) func TestConfigPrint(t *testing.T) { c := NewWithOpts(WithRun()) - err := c.flags.Parse([]string{"--eventsource.enable-thread=false", "--config-file=_fixtures/fibratus.yml"}) + err := c.flags.Parse([]string{"--filters.match-all=false", "--config-file=_fixtures/fibratus.yml"}) require.NoError(t, c.viper.BindPFlags(c.flags)) require.NoError(t, err) require.NoError(t, c.TryLoadFile(c.GetConfigFile())) diff --git a/pkg/config/schema_windows.go b/pkg/config/schema.go similarity index 97% rename from pkg/config/schema_windows.go rename to pkg/config/schema.go index a18907cc7..19e95a811 100644 --- a/pkg/config/schema_windows.go +++ b/pkg/config/schema.go @@ -18,9 +18,7 @@ package config -import ( - _ "embed" -) +import _ "embed" //go:embed config.schema.json var configSchema string diff --git a/pkg/config/transformer.go b/pkg/config/transformer.go index c2d6fb331..96b214b1d 100644 --- a/pkg/config/transformer.go +++ b/pkg/config/transformer.go @@ -1,5 +1,3 @@ -//go:build windows - /* * Copyright 2019-2020 by Nedim Sabic Sabic * https://www.fibratus.io @@ -22,13 +20,14 @@ package config import ( "fmt" + "reflect" + "github.com/rabbitstack/fibratus/pkg/aggregator/transformers" "github.com/rabbitstack/fibratus/pkg/aggregator/transformers/remove" "github.com/rabbitstack/fibratus/pkg/aggregator/transformers/rename" "github.com/rabbitstack/fibratus/pkg/aggregator/transformers/replace" "github.com/rabbitstack/fibratus/pkg/aggregator/transformers/tags" "github.com/rabbitstack/fibratus/pkg/aggregator/transformers/trim" - "reflect" ) var errTransformerConfig = func(t string, err error) error { return fmt.Errorf("%s transformer invalid config: %v", t, err) } diff --git a/pkg/config/transformer_test.go b/pkg/config/transformer_test.go index eaed5b497..f16d87c19 100644 --- a/pkg/config/transformer_test.go +++ b/pkg/config/transformer_test.go @@ -1,5 +1,3 @@ -//go:build windows - /* * Copyright 2019-2020 by Nedim Sabic Sabic * https://www.fibratus.io @@ -21,8 +19,9 @@ package config import ( - "github.com/stretchr/testify/require" "testing" + + "github.com/stretchr/testify/require" ) func TestTransformers(t *testing.T) { diff --git a/pkg/handle/snapshotter_test.go b/pkg/handle/snapshotter_test.go index dded81253..1453b69cd 100644 --- a/pkg/handle/snapshotter_test.go +++ b/pkg/handle/snapshotter_test.go @@ -35,7 +35,9 @@ func TestInitSnapshot(t *testing.T) { ch <- true t.Fatal("snapshot callback was not triggered") }) - snap := NewSnapshotter(&config.Config{InitHandleSnapshot: true}, func(total, known uint64) { + cfg := &config.Config{} + cfg.InitHandleSnapshot = true + snap := NewSnapshotter(cfg, func(total, known uint64) { ch <- true }) require.NotNil(t, snap) @@ -43,7 +45,10 @@ func TestInitSnapshot(t *testing.T) { } func TestFindHandles(t *testing.T) { - snap := NewSnapshotter(&config.Config{InitHandleSnapshot: true, EnumerateHandles: true}, nil) + cfg := &config.Config{} + cfg.InitHandleSnapshot = true + cfg.EnumerateHandles = true + snap := NewSnapshotter(cfg, nil) handles, err := snap.FindHandles(uint32(os.Getppid())) require.NoError(t, err) require.NotEmpty(t, handles) diff --git a/pkg/symbolize/symbolizer_test.go b/pkg/symbolize/symbolizer_test.go index c13df81ee..38426f169 100644 --- a/pkg/symbolize/symbolizer_test.go +++ b/pkg/symbolize/symbolizer_test.go @@ -82,7 +82,8 @@ func (r *MockResolver) Cleanup(proc windows.Handle) { func TestLoadKernelModuleSymbolTables(t *testing.T) { r := new(MockResolver) - c := &config.Config{SymbolizeKernelAddresses: true} + c := &config.Config{} + c.SymbolizeKernelAddresses = true psnap := new(ps.SnapshotterMock) @@ -307,9 +308,8 @@ func TestProcessCallstack(t *testing.T) { func TestKernelCallstackSymbolizationFromDriverStore(t *testing.T) { r := new(MockResolver) - c := &config.Config{ - SymbolizeKernelAddresses: false, - } + c := &config.Config{} + c.SymbolizeKernelAddresses = false psnap := new(ps.SnapshotterMock) s := NewSymbolizer(r, psnap, c, false) From 6da200f943ebbfa123ae51a6bf6dd5690cdf343f Mon Sep 17 00:00:00 2001 From: Mostafa Moradian Date: Mon, 10 Aug 2026 23:36:31 +0200 Subject: [PATCH 24/28] refactor(event): define Linux-native event semantics Separate Linux/Windows event types, parameters, queues, formatting, and marshalling while retaining shared behavior. Remove Windows-only Linux stubs, distinguish process/thread clones via clone flags, and add Linux coverage. --- ...stackwalk_linux.go => batch_linux_test.go} | 23 +- .../{batch_test.go => batch_windows_test.go} | 2 - pkg/event/bitset.go | 4 +- pkg/event/{enum_linux.go => bitset_linux.go} | 2 + ..._capture_linux.go => bitset_linux_test.go} | 15 +- pkg/event/bitset_windows.go | 21 ++ ...{bitset_test.go => bitset_windows_test.go} | 2 - pkg/event/{enum.go => enum_windows.go} | 2 - pkg/event/event.go | 5 +- pkg/event/event_linux.go | 79 +---- pkg/event/event_linux_test.go | 21 +- pkg/event/flags.go | 251 +--------------- pkg/event/flags_test.go | 20 +- pkg/event/flags_windows.go | 240 ++++++++++++++++ pkg/event/formatter.go | 62 +++- pkg/event/formatter_linux.go | 52 +--- pkg/event/formatter_linux_test.go | 44 +++ pkg/event/formatter_windows.go | 77 ++--- ...tter_test.go => formatter_windows_test.go} | 2 - pkg/event/marshaller.go | 8 + pkg/event/marshaller_linux.go | 38 ++- pkg/event/marshaller_linux_test.go | 38 +++ pkg/event/marshaller_windows.go | 10 + ...ler_test.go => marshaller_windows_test.go} | 2 - pkg/event/metainfo.go | 54 ++++ pkg/event/metainfo_linux.go | 68 +---- pkg/event/metainfo_windows.go | 39 --- pkg/event/param.go | 194 +++++++------ pkg/event/param_capture_windows.go | 76 ----- pkg/event/param_linux.go | 175 ++++++------ pkg/event/param_test.go | 23 +- pkg/event/param_windows.go | 270 ++++++++++-------- pkg/event/params/names.go | 147 ---------- pkg/event/params/names_linux.go | 30 ++ pkg/event/params/names_windows.go | 91 ++++++ pkg/event/params/param_types.go | 119 +++----- pkg/event/params/types_linux.go | 33 +++ pkg/event/params/types_windows.go | 44 +++ pkg/event/pid_linux.go | 3 + pkg/event/pid_windows.go | 3 + pkg/event/queue.go | 25 +- pkg/event/queue_linux.go | 29 ++ .../{flags_linux.go => queue_linux_test.go} | 24 +- pkg/event/queue_windows.go | 48 ++++ .../{queue_test.go => queue_windows_test.go} | 2 - .../{stackwalk.go => stackwalk_windows.go} | 2 - ...walk_test.go => stackwalk_windows_test.go} | 2 - pkg/event/template.go | 11 +- pkg/event/types_linux.go | 87 +++--- 49 files changed, 1360 insertions(+), 1259 deletions(-) rename pkg/event/{stackwalk_linux.go => batch_linux_test.go} (60%) rename pkg/event/{batch_test.go => batch_windows_test.go} (99%) rename pkg/event/{enum_linux.go => bitset_linux.go} (92%) rename pkg/event/{param_capture_linux.go => bitset_linux_test.go} (66%) create mode 100644 pkg/event/bitset_windows.go rename pkg/event/{bitset_test.go => bitset_windows_test.go} (99%) rename pkg/event/{enum.go => enum_windows.go} (99%) create mode 100644 pkg/event/flags_windows.go create mode 100644 pkg/event/formatter_linux_test.go rename pkg/event/{formatter_test.go => formatter_windows_test.go} (99%) create mode 100644 pkg/event/marshaller_linux_test.go rename pkg/event/{marshaller_test.go => marshaller_windows_test.go} (99%) create mode 100644 pkg/event/metainfo.go delete mode 100644 pkg/event/param_capture_windows.go create mode 100644 pkg/event/params/names_linux.go create mode 100644 pkg/event/params/names_windows.go create mode 100644 pkg/event/params/types_linux.go create mode 100644 pkg/event/params/types_windows.go create mode 100644 pkg/event/queue_linux.go rename pkg/event/{flags_linux.go => queue_linux_test.go} (68%) create mode 100644 pkg/event/queue_windows.go rename pkg/event/{queue_test.go => queue_windows_test.go} (99%) rename pkg/event/{stackwalk.go => stackwalk_windows.go} (99%) rename pkg/event/{stackwalk_test.go => stackwalk_windows_test.go} (99%) diff --git a/pkg/event/stackwalk_linux.go b/pkg/event/batch_linux_test.go similarity index 60% rename from pkg/event/stackwalk_linux.go rename to pkg/event/batch_linux_test.go index 7d3684f51..23f2766dc 100644 --- a/pkg/event/stackwalk_linux.go +++ b/pkg/event/batch_linux_test.go @@ -20,17 +20,18 @@ package event -// StackwalkDecorator is a no-op on Linux. Callstack enrichment -// via StackWalk events is a Windows ETW concept. -type StackwalkDecorator struct{} +import ( + "encoding/json" + "testing" -// NewStackwalkDecorator constructs a no-op stackwalk decorator. -func NewStackwalkDecorator(_ *Queue) *StackwalkDecorator { - return &StackwalkDecorator{} -} - -func (s *StackwalkDecorator) Push(_ *Event) {} + "github.com/stretchr/testify/require" +) -func (s *StackwalkDecorator) Pop(e *Event) *Event { return e } +func TestLinuxBatchMarshalJSON(t *testing.T) { + batch := NewBatch(&Event{PID: 42, Type: Execve}, &Event{PID: 43, Type: Exit}) + require.EqualValues(t, 2, batch.Len()) -func (s *StackwalkDecorator) Stop() {} + var events []map[string]interface{} + require.NoError(t, json.Unmarshal(batch.MarshalJSON(), &events)) + require.Len(t, events, 2) +} diff --git a/pkg/event/batch_test.go b/pkg/event/batch_windows_test.go similarity index 99% rename from pkg/event/batch_test.go rename to pkg/event/batch_windows_test.go index 0d2fe6826..e53039d1b 100644 --- a/pkg/event/batch_test.go +++ b/pkg/event/batch_windows_test.go @@ -1,5 +1,3 @@ -//go:build windows - /* * Copyright 2019-2020 by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/pkg/event/bitset.go b/pkg/event/bitset.go index abfb0a157..fb22e1e02 100644 --- a/pkg/event/bitset.go +++ b/pkg/event/bitset.go @@ -56,7 +56,7 @@ func (b *BitSets) SetBit(bs BitSetType, typ Type) { if b.types == nil { b.types = bitset.New(uint(MaxTypeID() + 1)) } - b.types.Set(uint(typ.HookID())) + b.types.Set(typeBitIndex(typ)) case CategoryBitSet: if b.cats == nil { @@ -82,7 +82,7 @@ func (b *BitSets) SetCategoryBit(c Category) { // Otherwise, event id bitset and last category bitset // are tested for respective bits. func (b *BitSets) IsBitSet(evt *Event) bool { - if b.types != nil && b.types.Test(uint(evt.Type.HookID())) { + if b.types != nil && b.types.Test(typeBitIndex(evt.Type)) { return true } return (b.bitmask != nil && b.bitmask.IsSet(evt.Type.ID())) || diff --git a/pkg/event/enum_linux.go b/pkg/event/bitset_linux.go similarity index 92% rename from pkg/event/enum_linux.go rename to pkg/event/bitset_linux.go index 7ed359caa..f78bc4079 100644 --- a/pkg/event/enum_linux.go +++ b/pkg/event/bitset_linux.go @@ -19,3 +19,5 @@ */ package event + +func typeBitIndex(typ Type) uint { return typ.ID() } diff --git a/pkg/event/param_capture_linux.go b/pkg/event/bitset_linux_test.go similarity index 66% rename from pkg/event/param_capture_linux.go rename to pkg/event/bitset_linux_test.go index c1b2c661a..1385c4574 100644 --- a/pkg/event/param_capture_linux.go +++ b/pkg/event/bitset_linux_test.go @@ -20,10 +20,15 @@ package event -import "github.com/rabbitstack/fibratus/pkg/event/params" +import ( + "testing" -// NewParamFromCapture builds a parameter instance from the restored capture state. -// Captures are not wired on Linux yet, so enrichment is deferred. -func NewParamFromCapture(name string, typ params.Type, value params.Value, _ Type) *Param { - return &Param{Name: name, Type: typ, Value: value} + "github.com/stretchr/testify/assert" +) + +func TestLinuxBitSets(t *testing.T) { + bitsets := &BitSets{} + bitsets.SetBit(TypeBitSet, Execve) + assert.True(t, bitsets.IsBitSet(&Event{Type: Execve})) + assert.False(t, bitsets.IsBitSet(&Event{Type: Exit})) } diff --git a/pkg/event/bitset_windows.go b/pkg/event/bitset_windows.go new file mode 100644 index 000000000..0a07df44c --- /dev/null +++ b/pkg/event/bitset_windows.go @@ -0,0 +1,21 @@ +/* + * Copyright 2026 by Mostafa Moradian + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package event + +func typeBitIndex(typ Type) uint { return uint(typ.HookID()) } diff --git a/pkg/event/bitset_test.go b/pkg/event/bitset_windows_test.go similarity index 99% rename from pkg/event/bitset_test.go rename to pkg/event/bitset_windows_test.go index 84903ac5c..df69110db 100644 --- a/pkg/event/bitset_test.go +++ b/pkg/event/bitset_windows_test.go @@ -1,5 +1,3 @@ -//go:build windows - /* * Copyright 2021-2022 by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/pkg/event/enum.go b/pkg/event/enum_windows.go similarity index 99% rename from pkg/event/enum.go rename to pkg/event/enum_windows.go index 326f81346..e4cd47c44 100644 --- a/pkg/event/enum.go +++ b/pkg/event/enum_windows.go @@ -1,5 +1,3 @@ -//go:build windows - /* * Copyright 2021-2022 by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/pkg/event/event.go b/pkg/event/event.go index 336ec7dc3..a0a8e4c6b 100644 --- a/pkg/event/event.go +++ b/pkg/event/event.go @@ -76,7 +76,7 @@ type Event struct { // PID is the identifier of the process that generated the event. PID PID `json:"pid"` // Tid is the thread identifier of the thread that generated the event. - Tid uint32 `json:"tid"` + Tid TID `json:"tid"` // Evasions is the bitmask that stores detected evasion types on this event. Evasions uint32 `json:"-"` // Type is the internal representation of the event. This field should be @@ -101,8 +101,7 @@ type Event struct { // PS represents process' metadata and its allocated resources such as handles, DLLs, etc. PS *pstypes.PS `json:"ps,omitempty"` // Callstack represents the call stack for the thread that generated the event. - Callstack callstack.Callstack `json:"callstack"` - + Callstack callstack.Callstack `json:"callstack,omitempty"` // mmux guards the metadata map mmux sync.RWMutex } diff --git a/pkg/event/event_linux.go b/pkg/event/event_linux.go index 493ae4616..52d873418 100644 --- a/pkg/event/event_linux.go +++ b/pkg/event/event_linux.go @@ -20,75 +20,24 @@ package event -import ( - "encoding/json" - "fmt" +import "github.com/rabbitstack/fibratus/pkg/event/params" - capver "github.com/rabbitstack/fibratus/pkg/cap/version" -) +const cloneThread = uint64(0x00010000) -func (e *Event) IsCreateFile() bool { return false } -func (e *Event) IsCreateProcess() bool { return e.Type == CreateProcess || e.Type == Execve || e.Type == Clone } -func (e *Event) IsCreateProcessInternal() bool { return false } -func (e *Event) IsCreateThread() bool { return false } -func (e *Event) IsCloseFile() bool { return false } -func (e *Event) IsCreateHandle() bool { return false } -func (e *Event) IsCloseHandle() bool { return false } -func (e *Event) IsDeleteFile() bool { return false } -func (e *Event) IsRenameFile() bool { return false } -func (e *Event) IsEnumDirectory() bool { return false } -func (e *Event) IsTerminateProcess() bool { return e.Type == TerminateProcess || e.Type == Exit } -func (e *Event) IsTerminateThread() bool { return false } -func (e *Event) IsUnloadModule() bool { return false } -func (e *Event) IsLoadModule() bool { return false } -func (e *Event) IsLoadModuleInternal() bool { return false } -func (e *Event) IsModuleRundown() bool { return false } -func (e *Event) IsFileOpEnd() bool { return false } -func (e *Event) IsRegSetValue() bool { return false } -func (e *Event) IsRegSetValueInternal() bool { return false } -func (e *Event) IsRegCreateKey() bool { return false } -func (e *Event) IsProcessRundown() bool { return e.Type == ProcessRundown } -func (e *Event) IsProcessRundownInternal() bool { return false } -func (e *Event) IsVirtualAlloc() bool { return false } -func (e *Event) IsMapViewFile() bool { return false } -func (e *Event) IsUnmapViewFile() bool { return false } -func (e *Event) IsStackWalk() bool { return false } -func (e *Event) IsOpenThread() bool { return false } -func (e *Event) IsOpenProcess() bool { return false } -func (e *Event) IsNetworkTCP() bool { return false } -func (e *Event) IsNetworkUDP() bool { return false } -func (e *Event) IsDNS() bool { return false } -func (e *Event) IsRundown() bool { return e.IsProcessRundown() } -func (e *Event) IsSuccess() bool { return true } -func (e *Event) IsRundownProcessed() bool { return false } -func (e *Event) IsCreateDisposition() bool { return false } -func (e *Event) IsOverwriteDisposition() bool { return false } -func (e *Event) IsOpenDisposition() bool { return false } -func (e *Event) IsCreateRemoteThread() bool { return false } -func (e *Event) IsSurrogateProcess() bool { return false } -func (e *Event) IsSystemPid() bool { return e.PID == 0 || e.PID == 1 } -func (e *Event) IsState() bool { return e.Type.OnlyState() } - -// PartialKey returns a key used to deduplicate sequence partials. -// On Linux this combines the event type with the process identifier. -func (e *Event) PartialKey() uint64 { - return uint64(e.Type)<<32 | uint64(e.PID) +// IsCreateProcess reports whether clone creates a new process. +func (e *Event) IsCreateProcess() bool { + return e.Type == Clone && e.Params.TryGetUint64(params.CloneFlags)&cloneThread == 0 } -// HookID returns the stable bitset index for this type. -func (t Type) HookID() uint16 { return uint16(t) } - -// MarshalJSON serializes the event to JSON. -func (e *Event) MarshalJSON() []byte { - b, err := json.Marshal(e) - if err != nil { - return []byte("{}") - } - return b +// IsCreateThread reports whether clone creates a thread in the current process. +func (e *Event) IsCreateThread() bool { + return e.Type == Clone && e.Params.TryGetUint64(params.CloneFlags)&cloneThread != 0 } -// UnmarshalRaw recovers the event from a capture buffer. -// Captures are not wired on Linux yet. -func (e *Event) UnmarshalRaw(_ []byte, _ capver.Version) error { - return fmt.Errorf("event capture unmarshalling is not implemented on Linux") +// IsTerminateProcess reports whether the event exits a process. +func (e *Event) IsTerminateProcess() bool { return e.Type == Exit } + +// PartialKey returns a key used to deduplicate sequence partials. +func (e *Event) PartialKey() uint64 { + return uint64(e.Type)<<32 | uint64(e.PID) } diff --git a/pkg/event/event_linux_test.go b/pkg/event/event_linux_test.go index 79a6ad5e3..0a3efa597 100644 --- a/pkg/event/event_linux_test.go +++ b/pkg/event/event_linux_test.go @@ -29,18 +29,29 @@ import ( ) func TestLinuxParamBasics(t *testing.T) { - p := NewParam(params.ProcessID, params.PID, uint32(42)) + p := NewParam(params.ProcessID, params.PID, uint64(42)) require.NotNil(t, p) assert.Equal(t, "42", p.String()) pars := Params{} - pars.Append(params.ProcessName, params.UnicodeString, "bash") + pars.Append(params.ProcessName, params.String, "bash") assert.Equal(t, "bash", pars.MustGetString(params.ProcessName)) } func TestLinuxEventTypeHelpers(t *testing.T) { e := &Event{Type: Execve, PID: 1} - assert.True(t, e.IsCreateProcess()) - assert.False(t, e.IsStackWalk()) - assert.Equal(t, uint16(Execve), e.Type.HookID()) + assert.False(t, e.IsCreateProcess()) + assert.Equal(t, RawSyscallTracepoint, e.Type.Source()) + assert.Equal(t, Process, e.Type.Category()) + assert.Equal(t, uint(Execve), e.Type.ID()) + + processClone := &Event{Type: Clone, Params: Params{}} + processClone.Params.Append(params.CloneFlags, params.Uint64, uint64(0)) + assert.True(t, processClone.IsCreateProcess()) + assert.False(t, processClone.IsCreateThread()) + + threadClone := &Event{Type: Clone, Params: Params{}} + threadClone.Params.Append(params.CloneFlags, params.Uint64, cloneThread) + assert.False(t, threadClone.IsCreateProcess()) + assert.True(t, threadClone.IsCreateThread()) } diff --git a/pkg/event/flags.go b/pkg/event/flags.go index 8cd50dd01..cf5a6878c 100644 --- a/pkg/event/flags.go +++ b/pkg/event/flags.go @@ -1,5 +1,3 @@ -//go:build windows - /* * Copyright 2021-2022 by Nedim Sabic Sabic * https://www.fibratus.io @@ -20,14 +18,9 @@ package event -import ( - "strings" - - "github.com/rabbitstack/fibratus/pkg/sys" - "golang.org/x/sys/windows" -) +import "strings" -// ParamFlag defines the mapping between the flag value and its symbolical name. +// ParamFlag defines the mapping between a flag value and its symbolic name. type ParamFlag struct { Name string Value uint64 @@ -37,240 +30,22 @@ func (f ParamFlag) eval(v uint64) bool { return (v == 0 && f.Value == 0) || (f.Value != 0 && (v&f.Value) == f.Value && v != 0) } -// ParamFlags represents the type alias for the event parameter flags +// ParamFlags maps parameter bit flags to symbolic names. type ParamFlags []ParamFlag -// String produces a string with all flags present in the bitmask and delimited -// with the `|` separator. -func (flags ParamFlags) String(f uint64) string { +// String returns the names of all flags in the bitmask, separated by pipes. +func (flags ParamFlags) String(value uint64) string { var ( - n strings.Builder - s string + names strings.Builder + separator string ) for _, flag := range flags { - if flag.eval(f) { - n.WriteString(s) - n.WriteString(flag.Name) - s = "|" - // remove current flags value to avoid duplicates - f &= ^flag.Value + if flag.eval(value) { + names.WriteString(separator) + names.WriteString(flag.Name) + separator = "|" + value &= ^flag.Value } } - return n.String() -} - -const ( - // PsApplicationID identifies the packaged process - PsApplicationID = 0x00000001 - // PsWOW64 indicates if the 32-bit process is created in 64-bit Windows system - PsWOW64 = 0x00000002 - // PsProtected process is to be run as a protected process. The system restricts - // access to protected processes and the threads of protected processes. - PsProtected = 0x00000004 - // PsPackaged represents a process packaged with the MSIX technology and thus has - // package identity. - PsPackaged = 0x00000008 -) - -// PsCreationFlags describes the process creation flags. -var PsCreationFlags = []ParamFlag{ - {"APPLICATION_ID", PsApplicationID}, - {"WOW64", PsWOW64}, - {"PROTECTED", PsProtected}, - {"PACKAGED", PsPackaged}, -} - -// AllAccess represents the maximum process/thread access right -const AllAccess = windows.STANDARD_RIGHTS_REQUIRED | windows.SYNCHRONIZE | 0xFFFF - -// PsAccessRightFlags describes flags for the process access rights. -var PsAccessRightFlags = []ParamFlag{ - {"ALL_ACCESS", AllAccess}, - {"DELETE", windows.DELETE}, - {"READ_CONTROL", windows.READ_CONTROL}, - {"SYNCHRONIZE", windows.SYNCHRONIZE}, - {"WRITE_DAC", windows.WRITE_DAC}, - {"WRITE_OWNER", windows.WRITE_OWNER}, - {"GENERIC_READ", windows.GENERIC_READ}, - {"ACCESS_SYSTEM_SECURITY", windows.ACCESS_SYSTEM_SECURITY}, - {"TERMINATE", windows.PROCESS_TERMINATE}, - {"CREATE_THREAD", windows.PROCESS_CREATE_THREAD}, - {"VM_OPERATION", windows.PROCESS_VM_OPERATION}, - {"VM_READ", windows.PROCESS_VM_READ}, - {"VM_WRITE", windows.PROCESS_VM_WRITE}, - {"DUP_HANDLE", windows.PROCESS_DUP_HANDLE}, - {"CREATE_PROCESS", windows.PROCESS_CREATE_PROCESS}, - {"SET_QUOTA", windows.PROCESS_SET_QUOTA}, - {"SET_INFORMATION", windows.PROCESS_SET_INFORMATION}, - {"QUERY_INFORMATION", windows.PROCESS_QUERY_INFORMATION}, - {"SUSPEND_RESUME", windows.PROCESS_SUSPEND_RESUME}, - {"QUERY_LIMITED_INFORMATION", windows.PROCESS_QUERY_LIMITED_INFORMATION}, -} - -// ThreadAccessRightFlags describes flags for the thread access rights. -var ThreadAccessRightFlags = []ParamFlag{ - {"ALL_ACCESS", AllAccess}, - {"DELETE", windows.DELETE}, - {"READ_CONTROL", windows.READ_CONTROL}, - {"SYNCHRONIZE", windows.SYNCHRONIZE}, - {"WRITE_DAC", windows.WRITE_DAC}, - {"WRITE_OWNER", windows.WRITE_OWNER}, - {"TERMINATE", windows.THREAD_TERMINATE}, - {"SUSPEND_THREAD", windows.THREAD_SUSPEND_RESUME}, - {"GET_CONTEXT", windows.THREAD_GET_CONTEXT}, - {"SET_CONTEXT", windows.THREAD_SET_CONTEXT}, - {"SET_INFORMATION", windows.THREAD_SET_INFORMATION}, - {"QUERY_INFORMATION", windows.THREAD_QUERY_INFORMATION}, - {"SET_THREAD_TOKEN", windows.THREAD_SET_THREAD_TOKEN}, - {"IMPERSONATE", windows.THREAD_IMPERSONATE}, - {"DIRECT_IMPERSONATION", windows.THREAD_DIRECT_IMPERSONATION}, - {"SET_LIMITED_INFORMATION", windows.THREAD_SET_LIMITED_INFORMATION}, - {"QUERY_LIMITED_INFORMATION", windows.THREAD_QUERY_LIMITED_INFORMATION}, -} - -// FileAttributeFlags describes file attribute flags. -var FileAttributeFlags = []ParamFlag{ - {"READ_ONLY", windows.FILE_ATTRIBUTE_READONLY}, - {"HIDDEN", windows.FILE_ATTRIBUTE_HIDDEN}, - {"SYSTEM", windows.FILE_ATTRIBUTE_SYSTEM}, - {"DIRECTORY", windows.FILE_ATTRIBUTE_DIRECTORY}, - {"ARCHIVE", windows.FILE_ATTRIBUTE_ARCHIVE}, - {"DEVICE", windows.FILE_ATTRIBUTE_DEVICE}, - {"NORMAL", windows.FILE_ATTRIBUTE_NORMAL}, - {"TEMPORARY", windows.FILE_ATTRIBUTE_TEMPORARY}, - {"SPARSE", windows.FILE_ATTRIBUTE_SPARSE_FILE}, - {"JUNCTION", windows.FILE_ATTRIBUTE_REPARSE_POINT}, - {"COMPRESSED", windows.FILE_ATTRIBUTE_COMPRESSED}, - {"OFFLINE", windows.FILE_ATTRIBUTE_OFFLINE}, - {"UNINDEXED", windows.FILE_ATTRIBUTE_NOT_CONTENT_INDEXED}, - {"ENCRYPTED", windows.FILE_ATTRIBUTE_ENCRYPTED}, - {"STREAM", windows.FILE_ATTRIBUTE_INTEGRITY_STREAM}, - {"VIRTUAL", windows.FILE_ATTRIBUTE_VIRTUAL}, - {"NO_SCRUB", windows.FILE_ATTRIBUTE_NO_SCRUB_DATA}, - {"RECALL_OPEN", windows.FILE_ATTRIBUTE_RECALL_ON_OPEN}, - {"RECALL_ACCESS", windows.FILE_ATTRIBUTE_RECALL_ON_DATA_ACCESS}, - {"PINNED", 0x80000}, - {"UNPINNED", 0x100000}, -} - -// FileCreateOptionsFlags describes file create options flags -var FileCreateOptionsFlags = []ParamFlag{ - {"DIRECTORY_FILE", windows.FILE_DIRECTORY_FILE}, - {"WRITE_THROUGH", windows.FILE_WRITE_THROUGH}, - {"SEQUENTIAL_ONLY", windows.FILE_SEQUENTIAL_ONLY}, - {"NO_INTERMEDIATE_BUFFERING", windows.FILE_NO_INTERMEDIATE_BUFFERING}, - {"SYNCHRONOUS_IO_ALERT", windows.FILE_SYNCHRONOUS_IO_ALERT}, - {"SYNCHRONOUS_IO_NONALERT", windows.FILE_SYNCHRONOUS_IO_NONALERT}, - {"NON_DIRECTORY_FILE", windows.FILE_NON_DIRECTORY_FILE}, - {"CREATE_TREE_CONNECTION", windows.FILE_CREATE_TREE_CONNECTION}, - {"COMPLETE_IF_OPLOCKED", windows.FILE_COMPLETE_IF_OPLOCKED}, - {"NO_EA_KNOWLEDGE", windows.FILE_NO_EA_KNOWLEDGE}, - {"OPEN_REMOTE_INSTANCE", windows.FILE_OPEN_REMOTE_INSTANCE}, - {"RANDOM_ACCESS", windows.FILE_RANDOM_ACCESS}, - {"DELETE_ON_CLOSE", windows.FILE_DELETE_ON_CLOSE}, - {"OPEN_BY_FILE_ID", windows.FILE_OPEN_BY_FILE_ID}, - {"FOR_BACKUP_INTENT", windows.FILE_OPEN_FOR_BACKUP_INTENT}, - {"NO_COMPRESSION", windows.FILE_NO_COMPRESSION}, - {"OPEN_REQUIRING_OPLOCK", windows.FILE_OPEN_REQUIRING_OPLOCK}, - {"DISALLOW_EXCLUSIVE", windows.FILE_DISALLOW_EXCLUSIVE}, - {"RESERVE_OPFILTER", windows.FILE_RESERVE_OPFILTER}, - {"OPEN_REPARSE_POINT", windows.FILE_OPEN_REPARSE_POINT}, - {"OPEN_NO_RECALL", windows.FILE_OPEN_NO_RECALL}, - {"OPEN_FOR_FREE_SPACE_QUERY", windows.FILE_OPEN_FOR_FREE_SPACE_QUERY}, -} - -// FileShareModeFlags describes file share mask flags -var FileShareModeFlags = []ParamFlag{ - {"DENY", 0}, - {"READ", windows.FILE_SHARE_READ}, - {"WRITE", windows.FILE_SHARE_WRITE}, - {"DELETE", windows.FILE_SHARE_DELETE}, -} - -// MemAllocationFlags describes virtual allocation/free type flags -var MemAllocationFlags = []ParamFlag{ - {"COMMIT", windows.MEM_COMMIT}, - {"RESERVE", windows.MEM_RESERVE}, - {"RESET", windows.MEM_RESET}, - {"RESET_UNDO", windows.MEM_RESET_UNDO}, - {"PHYSICAL", windows.MEM_PHYSICAL}, - {"LARGE_PAGES", windows.MEM_LARGE_PAGES}, - {"TOP_DOWN", windows.MEM_TOP_DOWN}, - {"RELEASE", windows.MEM_RELEASE}, - {"DECOMMIT", windows.MEM_DECOMMIT}, - {"WRITE_WATCH", windows.MEM_WRITE_WATCH}, -} - -// MemProtectionFlags represents memory protection option flags. -var MemProtectionFlags = []ParamFlag{ - {"NONE", 0}, - {"EXECUTE", windows.PAGE_EXECUTE}, - {"EXECUTE_READ", windows.PAGE_EXECUTE_READ}, - {"EXECUTE_READWRITE", windows.PAGE_EXECUTE_READWRITE}, - {"EXECUTE_WRITECOPY", windows.PAGE_EXECUTE_WRITECOPY}, - {"NOACCESS", windows.PAGE_NOACCESS}, - {"READONLY", windows.PAGE_READONLY}, - {"READWRITE", windows.PAGE_READWRITE}, - {"WRITECOPY", windows.PAGE_WRITECOPY}, - {"TARGETS_INVALID", windows.PAGE_TARGETS_INVALID}, - {"TARGETS_NO_UPDATE", windows.PAGE_TARGETS_NO_UPDATE}, - {"GUARD", windows.PAGE_GUARD}, - {"NOCACHE", windows.PAGE_NOCACHE}, - {"WRITECOMBINE", windows.PAGE_WRITECOMBINE}, -} - -// ViewProtectionFlags describes section protection flags. These -// have different values than the memory protection flags as they -// are reported by the kernel. -var ViewProtectionFlags = []ParamFlag{ - {"EXECUTE_READWRITE", sys.SectionRWX}, - {"EXECUTE_WRITECOPY", sys.SectionWXC}, - {"NOCACHE", sys.SectionNC}, - {"WRITECOMBINE", sys.SectionWCB}, - {"READONLY", sys.SectionR}, - {"EXECUTE", sys.SectionX}, - {"EXECUTE_READ", sys.SectionRX}, - {"READWRITE", sys.SectionRW}, - {"WRITECOPY", sys.SectionWC}, -} - -// DNSOptsFlags describes DNS query/response options. -var DNSOptsFlags = []ParamFlag{ - {"STANDARD", 0x00000000}, - {"ACCEPT_TRUNCATED_RESPONSE", 0x00000001}, - {"USE_TCP_ONLY", 0x00000002}, - {"NO_RECURSION", 0x00000004}, - {"BYPASS_CACHE", 0x00000008}, - {"NO_WIRE_QUERY", 0x00000010}, - {"NO_LOCAL_NAME", 0x00000020}, - {"NO_NETBT", 0x00000080}, - {"WIRE_ONLY", 0x00000100}, - {"RETURN_MESSAGE", 0x00000200}, - {"MULTICAST_ONLY", 0x00000400}, - {"NO_MULTICAST", 0x00000800}, - {"TREAT_AS_FQDN", 0x00001000}, - {"ADDRCONFIG", 0x00002000}, - {"DUAL_ADDR", 0x00004000}, - {"MULTICAST_WAIT", 0x00020000}, - {"MULTICAST_VERIFY", 0x00040000}, - {"DONT_RESET_TTL_VALUES", 0x00100000}, - {"DISABLE_IDN_ENCODING", 0x00200000}, - {"APPEND_MULTILABEL", 0x00800000}, -} - -// AccessMaskFlags describes the generic and specific access rights -var AccessMaskFlags = []ParamFlag{ - {"DELETE", windows.DELETE}, - {"READ_CONTROL", windows.READ_CONTROL}, - {"WRITE_DAC", windows.WRITE_DAC}, - {"WRITE_OWNER", windows.WRITE_OWNER}, - {"SYNCHRONIZE", windows.SYNCHRONIZE}, - {"STANDARD_RIGHTS_REQUIRED", windows.STANDARD_RIGHTS_REQUIRED}, - {"STANDARD_RIGHTS_ALL", windows.STANDARD_RIGHTS_ALL}, - {"ACCESS_SYSTEM_SECURITY", windows.ACCESS_SYSTEM_SECURITY}, - {"MAXIMUM_ALLOWED", windows.MAXIMUM_ALLOWED}, - {"GENERIC_READ", windows.GENERIC_READ}, - {"GENERIC_WRITE", windows.GENERIC_WRITE}, - {"GENERIC_EXECUTE", windows.GENERIC_EXECUTE}, - {"GENERIC_ALL", windows.GENERIC_ALL}, + return names.String() } diff --git a/pkg/event/flags_test.go b/pkg/event/flags_test.go index 4ce531ea7..78fdc6f5c 100644 --- a/pkg/event/flags_test.go +++ b/pkg/event/flags_test.go @@ -1,5 +1,3 @@ -//go:build windows - /* * Copyright 2021-2022 by Nedim Sabic Sabic * https://www.fibratus.io @@ -23,19 +21,23 @@ package event import "testing" func TestParamFlags(t *testing.T) { - var tests = []struct { + flags := ParamFlags{ + {Name: "ALL", Value: 0x3}, + {Name: "READ", Value: 0x1}, + {Name: "WRITE", Value: 0x2}, + } + tests := []struct { flag uint64 - flags ParamFlags expected string }{ - {0x1fffff, PsAccessRightFlags, "ALL_ACCESS"}, - {0x1400, PsAccessRightFlags, "QUERY_INFORMATION|QUERY_LIMITED_INFORMATION"}, - {0x1800, ThreadAccessRightFlags, "QUERY_LIMITED_INFORMATION"}, - {0x00000002, PsCreationFlags, "WOW64"}, + {0x3, "ALL"}, + {0x1, "READ"}, + {0x2, "WRITE"}, + {0, ""}, } for i, tt := range tests { - s := tt.flags.String(tt.flag) + s := flags.String(tt.flag) if s != tt.expected { t.Errorf("%d. %q flag mismatch: exp=%s got=%s", i, tt.expected, tt.expected, s) } diff --git a/pkg/event/flags_windows.go b/pkg/event/flags_windows.go new file mode 100644 index 000000000..3ff3aadbf --- /dev/null +++ b/pkg/event/flags_windows.go @@ -0,0 +1,240 @@ +/* + * Copyright 2021-2022 by Nedim Sabic Sabic + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package event + +import ( + "github.com/rabbitstack/fibratus/pkg/sys" + "golang.org/x/sys/windows" +) + +const ( + // PsApplicationID identifies the packaged process + PsApplicationID = 0x00000001 + // PsWOW64 indicates if the 32-bit process is created in 64-bit Windows system + PsWOW64 = 0x00000002 + // PsProtected process is to be run as a protected process. The system restricts + // access to protected processes and the threads of protected processes. + PsProtected = 0x00000004 + // PsPackaged represents a process packaged with the MSIX technology and thus has + // package identity. + PsPackaged = 0x00000008 +) + +// PsCreationFlags describes the process creation flags. +var PsCreationFlags = []ParamFlag{ + {"APPLICATION_ID", PsApplicationID}, + {"WOW64", PsWOW64}, + {"PROTECTED", PsProtected}, + {"PACKAGED", PsPackaged}, +} + +// AllAccess represents the maximum process/thread access right +const AllAccess = windows.STANDARD_RIGHTS_REQUIRED | windows.SYNCHRONIZE | 0xFFFF + +// PsAccessRightFlags describes flags for the process access rights. +var PsAccessRightFlags = []ParamFlag{ + {"ALL_ACCESS", AllAccess}, + {"DELETE", windows.DELETE}, + {"READ_CONTROL", windows.READ_CONTROL}, + {"SYNCHRONIZE", windows.SYNCHRONIZE}, + {"WRITE_DAC", windows.WRITE_DAC}, + {"WRITE_OWNER", windows.WRITE_OWNER}, + {"GENERIC_READ", windows.GENERIC_READ}, + {"ACCESS_SYSTEM_SECURITY", windows.ACCESS_SYSTEM_SECURITY}, + {"TERMINATE", windows.PROCESS_TERMINATE}, + {"CREATE_THREAD", windows.PROCESS_CREATE_THREAD}, + {"VM_OPERATION", windows.PROCESS_VM_OPERATION}, + {"VM_READ", windows.PROCESS_VM_READ}, + {"VM_WRITE", windows.PROCESS_VM_WRITE}, + {"DUP_HANDLE", windows.PROCESS_DUP_HANDLE}, + {"CREATE_PROCESS", windows.PROCESS_CREATE_PROCESS}, + {"SET_QUOTA", windows.PROCESS_SET_QUOTA}, + {"SET_INFORMATION", windows.PROCESS_SET_INFORMATION}, + {"QUERY_INFORMATION", windows.PROCESS_QUERY_INFORMATION}, + {"SUSPEND_RESUME", windows.PROCESS_SUSPEND_RESUME}, + {"QUERY_LIMITED_INFORMATION", windows.PROCESS_QUERY_LIMITED_INFORMATION}, +} + +// ThreadAccessRightFlags describes flags for the thread access rights. +var ThreadAccessRightFlags = []ParamFlag{ + {"ALL_ACCESS", AllAccess}, + {"DELETE", windows.DELETE}, + {"READ_CONTROL", windows.READ_CONTROL}, + {"SYNCHRONIZE", windows.SYNCHRONIZE}, + {"WRITE_DAC", windows.WRITE_DAC}, + {"WRITE_OWNER", windows.WRITE_OWNER}, + {"TERMINATE", windows.THREAD_TERMINATE}, + {"SUSPEND_THREAD", windows.THREAD_SUSPEND_RESUME}, + {"GET_CONTEXT", windows.THREAD_GET_CONTEXT}, + {"SET_CONTEXT", windows.THREAD_SET_CONTEXT}, + {"SET_INFORMATION", windows.THREAD_SET_INFORMATION}, + {"QUERY_INFORMATION", windows.THREAD_QUERY_INFORMATION}, + {"SET_THREAD_TOKEN", windows.THREAD_SET_THREAD_TOKEN}, + {"IMPERSONATE", windows.THREAD_IMPERSONATE}, + {"DIRECT_IMPERSONATION", windows.THREAD_DIRECT_IMPERSONATION}, + {"SET_LIMITED_INFORMATION", windows.THREAD_SET_LIMITED_INFORMATION}, + {"QUERY_LIMITED_INFORMATION", windows.THREAD_QUERY_LIMITED_INFORMATION}, +} + +// FileAttributeFlags describes file attribute flags. +var FileAttributeFlags = []ParamFlag{ + {"READ_ONLY", windows.FILE_ATTRIBUTE_READONLY}, + {"HIDDEN", windows.FILE_ATTRIBUTE_HIDDEN}, + {"SYSTEM", windows.FILE_ATTRIBUTE_SYSTEM}, + {"DIRECTORY", windows.FILE_ATTRIBUTE_DIRECTORY}, + {"ARCHIVE", windows.FILE_ATTRIBUTE_ARCHIVE}, + {"DEVICE", windows.FILE_ATTRIBUTE_DEVICE}, + {"NORMAL", windows.FILE_ATTRIBUTE_NORMAL}, + {"TEMPORARY", windows.FILE_ATTRIBUTE_TEMPORARY}, + {"SPARSE", windows.FILE_ATTRIBUTE_SPARSE_FILE}, + {"JUNCTION", windows.FILE_ATTRIBUTE_REPARSE_POINT}, + {"COMPRESSED", windows.FILE_ATTRIBUTE_COMPRESSED}, + {"OFFLINE", windows.FILE_ATTRIBUTE_OFFLINE}, + {"UNINDEXED", windows.FILE_ATTRIBUTE_NOT_CONTENT_INDEXED}, + {"ENCRYPTED", windows.FILE_ATTRIBUTE_ENCRYPTED}, + {"STREAM", windows.FILE_ATTRIBUTE_INTEGRITY_STREAM}, + {"VIRTUAL", windows.FILE_ATTRIBUTE_VIRTUAL}, + {"NO_SCRUB", windows.FILE_ATTRIBUTE_NO_SCRUB_DATA}, + {"RECALL_OPEN", windows.FILE_ATTRIBUTE_RECALL_ON_OPEN}, + {"RECALL_ACCESS", windows.FILE_ATTRIBUTE_RECALL_ON_DATA_ACCESS}, + {"PINNED", 0x80000}, + {"UNPINNED", 0x100000}, +} + +// FileCreateOptionsFlags describes file create options flags +var FileCreateOptionsFlags = []ParamFlag{ + {"DIRECTORY_FILE", windows.FILE_DIRECTORY_FILE}, + {"WRITE_THROUGH", windows.FILE_WRITE_THROUGH}, + {"SEQUENTIAL_ONLY", windows.FILE_SEQUENTIAL_ONLY}, + {"NO_INTERMEDIATE_BUFFERING", windows.FILE_NO_INTERMEDIATE_BUFFERING}, + {"SYNCHRONOUS_IO_ALERT", windows.FILE_SYNCHRONOUS_IO_ALERT}, + {"SYNCHRONOUS_IO_NONALERT", windows.FILE_SYNCHRONOUS_IO_NONALERT}, + {"NON_DIRECTORY_FILE", windows.FILE_NON_DIRECTORY_FILE}, + {"CREATE_TREE_CONNECTION", windows.FILE_CREATE_TREE_CONNECTION}, + {"COMPLETE_IF_OPLOCKED", windows.FILE_COMPLETE_IF_OPLOCKED}, + {"NO_EA_KNOWLEDGE", windows.FILE_NO_EA_KNOWLEDGE}, + {"OPEN_REMOTE_INSTANCE", windows.FILE_OPEN_REMOTE_INSTANCE}, + {"RANDOM_ACCESS", windows.FILE_RANDOM_ACCESS}, + {"DELETE_ON_CLOSE", windows.FILE_DELETE_ON_CLOSE}, + {"OPEN_BY_FILE_ID", windows.FILE_OPEN_BY_FILE_ID}, + {"FOR_BACKUP_INTENT", windows.FILE_OPEN_FOR_BACKUP_INTENT}, + {"NO_COMPRESSION", windows.FILE_NO_COMPRESSION}, + {"OPEN_REQUIRING_OPLOCK", windows.FILE_OPEN_REQUIRING_OPLOCK}, + {"DISALLOW_EXCLUSIVE", windows.FILE_DISALLOW_EXCLUSIVE}, + {"RESERVE_OPFILTER", windows.FILE_RESERVE_OPFILTER}, + {"OPEN_REPARSE_POINT", windows.FILE_OPEN_REPARSE_POINT}, + {"OPEN_NO_RECALL", windows.FILE_OPEN_NO_RECALL}, + {"OPEN_FOR_FREE_SPACE_QUERY", windows.FILE_OPEN_FOR_FREE_SPACE_QUERY}, +} + +// FileShareModeFlags describes file share mask flags +var FileShareModeFlags = []ParamFlag{ + {"DENY", 0}, + {"READ", windows.FILE_SHARE_READ}, + {"WRITE", windows.FILE_SHARE_WRITE}, + {"DELETE", windows.FILE_SHARE_DELETE}, +} + +// MemAllocationFlags describes virtual allocation/free type flags +var MemAllocationFlags = []ParamFlag{ + {"COMMIT", windows.MEM_COMMIT}, + {"RESERVE", windows.MEM_RESERVE}, + {"RESET", windows.MEM_RESET}, + {"RESET_UNDO", windows.MEM_RESET_UNDO}, + {"PHYSICAL", windows.MEM_PHYSICAL}, + {"LARGE_PAGES", windows.MEM_LARGE_PAGES}, + {"TOP_DOWN", windows.MEM_TOP_DOWN}, + {"RELEASE", windows.MEM_RELEASE}, + {"DECOMMIT", windows.MEM_DECOMMIT}, + {"WRITE_WATCH", windows.MEM_WRITE_WATCH}, +} + +// MemProtectionFlags represents memory protection option flags. +var MemProtectionFlags = []ParamFlag{ + {"NONE", 0}, + {"EXECUTE", windows.PAGE_EXECUTE}, + {"EXECUTE_READ", windows.PAGE_EXECUTE_READ}, + {"EXECUTE_READWRITE", windows.PAGE_EXECUTE_READWRITE}, + {"EXECUTE_WRITECOPY", windows.PAGE_EXECUTE_WRITECOPY}, + {"NOACCESS", windows.PAGE_NOACCESS}, + {"READONLY", windows.PAGE_READONLY}, + {"READWRITE", windows.PAGE_READWRITE}, + {"WRITECOPY", windows.PAGE_WRITECOPY}, + {"TARGETS_INVALID", windows.PAGE_TARGETS_INVALID}, + {"TARGETS_NO_UPDATE", windows.PAGE_TARGETS_NO_UPDATE}, + {"GUARD", windows.PAGE_GUARD}, + {"NOCACHE", windows.PAGE_NOCACHE}, + {"WRITECOMBINE", windows.PAGE_WRITECOMBINE}, +} + +// ViewProtectionFlags describes section protection flags. These +// have different values than the memory protection flags as they +// are reported by the kernel. +var ViewProtectionFlags = []ParamFlag{ + {"EXECUTE_READWRITE", sys.SectionRWX}, + {"EXECUTE_WRITECOPY", sys.SectionWXC}, + {"NOCACHE", sys.SectionNC}, + {"WRITECOMBINE", sys.SectionWCB}, + {"READONLY", sys.SectionR}, + {"EXECUTE", sys.SectionX}, + {"EXECUTE_READ", sys.SectionRX}, + {"READWRITE", sys.SectionRW}, + {"WRITECOPY", sys.SectionWC}, +} + +// DNSOptsFlags describes DNS query/response options. +var DNSOptsFlags = []ParamFlag{ + {"STANDARD", 0x00000000}, + {"ACCEPT_TRUNCATED_RESPONSE", 0x00000001}, + {"USE_TCP_ONLY", 0x00000002}, + {"NO_RECURSION", 0x00000004}, + {"BYPASS_CACHE", 0x00000008}, + {"NO_WIRE_QUERY", 0x00000010}, + {"NO_LOCAL_NAME", 0x00000020}, + {"NO_NETBT", 0x00000080}, + {"WIRE_ONLY", 0x00000100}, + {"RETURN_MESSAGE", 0x00000200}, + {"MULTICAST_ONLY", 0x00000400}, + {"NO_MULTICAST", 0x00000800}, + {"TREAT_AS_FQDN", 0x00001000}, + {"ADDRCONFIG", 0x00002000}, + {"DUAL_ADDR", 0x00004000}, + {"MULTICAST_WAIT", 0x00020000}, + {"MULTICAST_VERIFY", 0x00040000}, + {"DONT_RESET_TTL_VALUES", 0x00100000}, + {"DISABLE_IDN_ENCODING", 0x00200000}, + {"APPEND_MULTILABEL", 0x00800000}, +} + +// AccessMaskFlags describes the generic and specific access rights +var AccessMaskFlags = []ParamFlag{ + {"DELETE", windows.DELETE}, + {"READ_CONTROL", windows.READ_CONTROL}, + {"WRITE_DAC", windows.WRITE_DAC}, + {"WRITE_OWNER", windows.WRITE_OWNER}, + {"SYNCHRONIZE", windows.SYNCHRONIZE}, + {"STANDARD_RIGHTS_REQUIRED", windows.STANDARD_RIGHTS_REQUIRED}, + {"STANDARD_RIGHTS_ALL", windows.STANDARD_RIGHTS_ALL}, + {"ACCESS_SYSTEM_SECURITY", windows.ACCESS_SYSTEM_SECURITY}, + {"MAXIMUM_ALLOWED", windows.MAXIMUM_ALLOWED}, + {"GENERIC_READ", windows.GENERIC_READ}, + {"GENERIC_WRITE", windows.GENERIC_WRITE}, + {"GENERIC_EXECUTE", windows.GENERIC_EXECUTE}, + {"GENERIC_ALL", windows.GENERIC_ALL}, +} diff --git a/pkg/event/formatter.go b/pkg/event/formatter.go index d1181ada7..ce2d5e0c6 100644 --- a/pkg/event/formatter.go +++ b/pkg/event/formatter.go @@ -157,6 +157,49 @@ func NewFormatter(template string) (*Formatter, error) { }, nil } +// Format applies the template to the provided event. +func (f *Formatter) Format(evt *Event) []byte { + if evt == nil { + return []byte{} + } + values := map[string]interface{}{ + ts: evt.Timestamp.String(), + pid: strconv.FormatUint(uint64(evt.PID), 10), + tid: strconv.FormatUint(uint64(evt.Tid), 10), + seq: strconv.FormatUint(evt.Seq, 10), + cpu: strconv.FormatUint(uint64(evt.CPU), 10), + typ: evt.Name, + cat: evt.Category, + desc: evt.Description, + host: evt.Host, + meta: evt.Metadata.String(), + parameters: evt.Params.String(), + } + + if ps := evt.PS; ps != nil { + values[proc] = ps.Name + values[ppid] = strconv.FormatUint(uint64(ps.Ppid), 10) + values[cwd] = ps.Cwd + values[exe] = ps.Exe + values[cmd] = ps.Cmdline + if ps.Parent != nil { + values[pproc] = ps.Parent.Name + values[pexe] = ps.Parent.Exe + values[pcmd] = ps.Parent.Cmdline + } + addPlatformProcessFormatValues(ps, values) + } + addPlatformFormatValues(evt, values) + + if f.expandParamsDot { + for _, par := range evt.Params { + values[".Params."+caser.String(par.Name)] = par.String() + } + } + + return f.t.ExecuteString(values) +} + // ColorFormatter wraps a Formatter and re-renders each template tag with // ANSI colour codes before it is substituted into the output string. // @@ -205,6 +248,9 @@ func (f *ColorFormatter) Format(e *Event) []byte { // colourTag maps a bare tag name to its coloured string representation. func (f *ColorFormatter) colourTag(tag string, e *Event) string { + if value, ok := colourPlatformProcessTag(tag, e); ok { + return value + } switch tag { case seq: // sequence number is ok to render as dim gray @@ -273,13 +319,6 @@ func (f *ColorFormatter) colourTag(tag string, e *Event) string { } return colorizer.Span(colorizer.White, ps.Cwd) - case sid: - ps := e.PS - if ps == nil { - return colorizer.Span(colorizer.Gray, "N/A") - } - return colorizer.Span(colorizer.Gray, ps.SID) - case pproc: ps := e.PS if ps == nil || ps.Parent == nil { @@ -296,15 +335,8 @@ func (f *ColorFormatter) colourTag(tag string, e *Event) string { case parameters: return e.Params.Colorize() - case pe: - ps := e.PS - if ps == nil || ps.PE == nil { - return colorizer.Span(colorizer.Gray, "N/A") - } - return colorizer.Span(colorizer.Magenta, ps.PE.String()) - case cstack: - return fmt.Sprintf("\n%s", e.Callstack.Colorize()) + return colourPlatformTag(tag, e) } return "" diff --git a/pkg/event/formatter_linux.go b/pkg/event/formatter_linux.go index 8e3322ac5..8ac7533d0 100644 --- a/pkg/event/formatter_linux.go +++ b/pkg/event/formatter_linux.go @@ -20,54 +20,12 @@ package event -import "strconv" +import pstypes "github.com/rabbitstack/fibratus/pkg/ps/types" -// Format applies the template on the provided event. -func (f *Formatter) Format(evt *Event) []byte { - if evt == nil { - return []byte{} - } - values := map[string]interface{}{ - ts: evt.Timestamp.String(), - pid: strconv.FormatUint(uint64(evt.PID), 10), - tid: strconv.FormatUint(uint64(evt.Tid), 10), - seq: strconv.FormatUint(evt.Seq, 10), - cpu: strconv.FormatUint(uint64(evt.CPU), 10), - typ: evt.Name, - cat: evt.Category, - desc: evt.Description, - host: evt.Host, - meta: evt.Metadata.String(), - parameters: evt.Params.String(), - } +func addPlatformFormatValues(_ *Event, _ map[string]interface{}) {} - ps := evt.PS - if ps != nil { - values[proc] = ps.Name - values[ppid] = strconv.FormatUint(uint64(ps.Ppid), 10) - values[cwd] = ps.Cwd - values[exe] = ps.Exe - values[cmd] = ps.Cmdline - values[sid] = ps.SID - parent := ps.Parent - if parent != nil { - values[pproc] = parent.Name - values[pexe] = parent.Exe - values[pcmd] = parent.Cmdline - } - if ps.PE != nil { - values[pe] = ps.PE.String() - } - } - if !evt.Callstack.IsEmpty() { - values[cstack] = evt.Callstack.String() - } +func addPlatformProcessFormatValues(_ *pstypes.PS, _ map[string]interface{}) {} - if f.expandParamsDot { - for _, par := range evt.Params { - values[".Params."+caser.String(par.Name)] = par.String() - } - } +func colourPlatformTag(_ string, _ *Event) string { return "" } - return f.t.ExecuteString(values) -} +func colourPlatformProcessTag(_ string, _ *Event) (string, bool) { return "", false } diff --git a/pkg/event/formatter_linux_test.go b/pkg/event/formatter_linux_test.go new file mode 100644 index 000000000..5c016fd83 --- /dev/null +++ b/pkg/event/formatter_linux_test.go @@ -0,0 +1,44 @@ +//go:build linux + +/* + * Copyright 2026 by Mostafa Moradian + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package event + +import ( + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestLinuxFormatter(t *testing.T) { + formatter, err := NewFormatter("{{.Type}} pid={{.Pid}} tid={{.Tid}}") + require.NoError(t, err) + + event := &Event{ + Timestamp: time.Now(), + PID: 42, + Tid: 43, + Type: Execve, + Name: Execve.String(), + Category: Process, + } + assert.Equal(t, "execve pid=42 tid=43", string(formatter.Format(event))) +} diff --git a/pkg/event/formatter_windows.go b/pkg/event/formatter_windows.go index c441ae650..d75280b84 100644 --- a/pkg/event/formatter_windows.go +++ b/pkg/event/formatter_windows.go @@ -19,59 +19,42 @@ package event import ( - "strconv" -) + "fmt" -// Format applies the template on the provided event. -func (f *Formatter) Format(evt *Event) []byte { - if evt == nil { - return []byte{} - } - values := map[string]interface{}{ - ts: evt.Timestamp.String(), - pid: strconv.FormatUint(uint64(evt.PID), 10), - tid: strconv.FormatUint(uint64(evt.Tid), 10), - seq: strconv.FormatUint(evt.Seq, 10), - cpu: strconv.FormatUint(uint64(evt.CPU), 10), - typ: evt.Name, - cat: evt.Category, - desc: evt.Description, - host: evt.Host, - meta: evt.Metadata.String(), - parameters: evt.Params.String(), - } + pstypes "github.com/rabbitstack/fibratus/pkg/ps/types" + "github.com/rabbitstack/fibratus/pkg/util/colorizer" +) - // add process metadata - ps := evt.PS - if ps != nil { - values[proc] = ps.Name - values[ppid] = strconv.FormatUint(uint64(ps.Ppid), 10) - values[cwd] = ps.Cwd - values[exe] = ps.Exe - values[cmd] = ps.Cmdline - values[sid] = ps.SID - parent := ps.Parent - if parent != nil { - values[pproc] = parent.Name - values[pexe] = parent.Exe - values[pcmd] = parent.Cmdline - } - if ps.PE != nil { - values[pe] = ps.PE.String() - } - } - // add callstack summary +func addPlatformFormatValues(evt *Event, values map[string]interface{}) { if !evt.Callstack.IsEmpty() { values[cstack] = evt.Callstack.String() } +} - if f.expandParamsDot { - // expand all parameters into the map, so we can ask - // for specific parameter names in the template - for _, par := range evt.Params { - values[".Params."+caser.String(par.Name)] = par.String() - } +func addPlatformProcessFormatValues(ps *pstypes.PS, values map[string]interface{}) { + values[sid] = ps.SID + if ps.PE != nil { + values[pe] = ps.PE.String() } +} + +func colourPlatformTag(_ string, evt *Event) string { + return fmt.Sprintf("\n%s", evt.Callstack.Colorize()) +} - return f.t.ExecuteString(values) +func colourPlatformProcessTag(tag string, evt *Event) (string, bool) { + switch tag { + case sid: + if evt.PS == nil { + return colorizer.Span(colorizer.Gray, "N/A"), true + } + return colorizer.Span(colorizer.Gray, evt.PS.SID), true + case pe: + if evt.PS == nil || evt.PS.PE == nil { + return colorizer.Span(colorizer.Gray, "N/A"), true + } + return colorizer.Span(colorizer.Magenta, evt.PS.PE.String()), true + default: + return "", false + } } diff --git a/pkg/event/formatter_test.go b/pkg/event/formatter_windows_test.go similarity index 99% rename from pkg/event/formatter_test.go rename to pkg/event/formatter_windows_test.go index f5f534664..044a4c128 100644 --- a/pkg/event/formatter_test.go +++ b/pkg/event/formatter_windows_test.go @@ -1,5 +1,3 @@ -//go:build windows - /* * Copyright 2019-2020 by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/pkg/event/marshaller.go b/pkg/event/marshaller.go index 01008265f..973bc129c 100644 --- a/pkg/event/marshaller.go +++ b/pkg/event/marshaller.go @@ -24,6 +24,14 @@ import ( "unicode/utf8" ) +type serializationConfig struct { + handles bool + threads bool + modules bool + envs bool + pe bool +} + type jsonStream struct { buf []byte } diff --git a/pkg/event/marshaller_linux.go b/pkg/event/marshaller_linux.go index 0a3be0a01..a785ddda2 100644 --- a/pkg/event/marshaller_linux.go +++ b/pkg/event/marshaller_linux.go @@ -20,15 +20,31 @@ package event -var ( - // SerializeHandles indicates if handles are serialized as part of the process state - SerializeHandles bool - // SerializeThreads indicates if threads are serialized as part of the process state - SerializeThreads bool - // SerializeModules indicates if modules are serialized as part of the process state - SerializeModules bool - // SerializePE indicates if PE metadata are serialized as part of the process state - SerializePE bool - // SerializeEnvs indicates if the environment variables are serialized as part of the process state - SerializeEnvs bool +import ( + "encoding/json" + "fmt" + + capver "github.com/rabbitstack/fibratus/pkg/cap/version" ) + +// SerializeEnvs indicates if environment variables are serialized with process state. +var SerializeEnvs bool + +func serializationOptions() serializationConfig { + return serializationConfig{envs: SerializeEnvs} +} + +// MarshalJSON serializes the event to JSON. +func (e *Event) MarshalJSON() []byte { + type plainEvent Event + b, err := json.Marshal((*plainEvent)(e)) + if err != nil { + return []byte("{}") + } + return b +} + +// UnmarshalRaw recovers an event from a capture buffer. +func (e *Event) UnmarshalRaw(_ []byte, _ capver.Version) error { + return fmt.Errorf("event capture unmarshalling is not implemented on Linux") +} diff --git a/pkg/event/marshaller_linux_test.go b/pkg/event/marshaller_linux_test.go new file mode 100644 index 000000000..53e9b6c5c --- /dev/null +++ b/pkg/event/marshaller_linux_test.go @@ -0,0 +1,38 @@ +//go:build linux + +/* + * Copyright 2026 by Mostafa Moradian + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package event + +import ( + "encoding/json" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestLinuxMarshalJSON(t *testing.T) { + event := &Event{PID: 42, Tid: 43, Type: Execve, Name: Execve.String(), Category: Process} + var decoded map[string]interface{} + require.NoError(t, json.Unmarshal(event.MarshalJSON(), &decoded)) + assert.Equal(t, float64(42), decoded["pid"]) + assert.Equal(t, float64(43), decoded["tid"]) + assert.Equal(t, "execve", decoded["name"]) +} diff --git a/pkg/event/marshaller_windows.go b/pkg/event/marshaller_windows.go index 5ded48295..4afc9f6cc 100644 --- a/pkg/event/marshaller_windows.go +++ b/pkg/event/marshaller_windows.go @@ -51,6 +51,16 @@ var ( SerializeEnvs bool ) +func serializationOptions() serializationConfig { + return serializationConfig{ + handles: SerializeHandles, + threads: SerializeThreads, + modules: SerializeModules, + envs: SerializeEnvs, + pe: SerializePE, + } +} + // unmarshalTimestampErrors counts timestamp unmarshal errors var unmarshalTimestampErrors = expvar.NewInt("event.timestamp.unmarshal.errors") diff --git a/pkg/event/marshaller_test.go b/pkg/event/marshaller_windows_test.go similarity index 99% rename from pkg/event/marshaller_test.go rename to pkg/event/marshaller_windows_test.go index 81d2426ee..37be2a3e6 100644 --- a/pkg/event/marshaller_test.go +++ b/pkg/event/marshaller_windows_test.go @@ -1,5 +1,3 @@ -//go:build windows - /* * Copyright 2019-2020 by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/pkg/event/metainfo.go b/pkg/event/metainfo.go new file mode 100644 index 000000000..289196db4 --- /dev/null +++ b/pkg/event/metainfo.go @@ -0,0 +1,54 @@ +/* + * Copyright 2019-2020 by Nedim Sabic Sabic + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package event + +import ( + "cmp" + "slices" +) + +// Info describes an event's human-readable name, category, and purpose. +type Info struct { + Name string + Category Category + Description string +} + +// GetTypesMeta returns event type metadata without duplicate display names. +func GetTypesMeta() []Info { + infos := make([]Info, 0, len(events)) +outer: + for _, info := range events { + for _, existing := range infos { + if existing.Name == info.Name { + continue outer + } + } + infos = append(infos, info) + } + slices.SortFunc(infos, func(a, b Info) int { + return cmp.Or(cmp.Compare(a.Category, b.Category), cmp.Compare(a.Name, b.Name)) + }) + return infos +} + +// IsKnown reports whether the event name is registered. +func IsKnown(name string) bool { + return NameToType(name) != UnknownType +} diff --git a/pkg/event/metainfo_linux.go b/pkg/event/metainfo_linux.go index 4378f1a8a..667f598a3 100644 --- a/pkg/event/metainfo_linux.go +++ b/pkg/event/metainfo_linux.go @@ -22,42 +22,29 @@ package event import "slices" -type Info struct { - Name string - Category Category - Description string -} - var events = map[Type]Info{ - CreateProcess: {Name: "CreateProcess", Category: Process, Description: "Creates a new process"}, - Execve: {Name: "Execve", Category: Process, Description: "Executes a program"}, - TerminateProcess: {Name: "TerminateProcess", Category: Process, Description: "Terminates a process"}, - Exit: {Name: "Exit", Category: Process, Description: "Exits a process"}, - ProcessRundown: {Name: "ProcessRundown", Category: Process, Description: "Reports an existing process"}, - Clone: {Name: "Clone", Category: Process, Description: "Clones a process or thread"}, + Execve: {Name: "execve", Category: Process, Description: "Executes a program"}, + Exit: {Name: "exit", Category: Process, Description: "Exit all threads in a process"}, + Clone: {Name: "clone", Category: Process, Description: "Creates a child process or a thread"}, } var types = map[string]Type{ - "CreateProcess": CreateProcess, - "Execve": Execve, - "TerminateProcess": TerminateProcess, - "Exit": Exit, - "ProcessRundown": ProcessRundown, - "Clone": Clone, + "execve": Execve, + "exit": Exit, + "clone": Clone, } +// All returns all Linux event types. func All() []Type { - return []Type{CreateProcess, Execve, TerminateProcess, Exit, Clone} -} - -func AllWithState() []Type { - return append(All(), ProcessRundown) + return []Type{Execve, Exit, Clone} } +// MaxTypeID returns the largest Linux event type identifier. func MaxTypeID() uint16 { - return uint16(slices.Max(AllWithState())) + return uint16(slices.Max(All())) } +// TypeToEventInfo returns metadata for an event type. func TypeToEventInfo(typ Type) Info { if info, ok := events[typ]; ok { return info @@ -65,6 +52,7 @@ func TypeToEventInfo(typ Type) Info { return Info{Name: "N/A", Category: Unknown} } +// NameToType converts an event name to its type. func NameToType(name string) Type { if typ, ok := types[name]; ok { return typ @@ -72,37 +60,7 @@ func NameToType(name string) Type { return UnknownType } +// NameToTypes converts an event name to its possible internal types. func NameToTypes(name string) []Type { return []Type{NameToType(name)} } - -func GetTypesMeta() []Info { - infos := make([]Info, 0, len(events)) - for _, info := range events { - infos = append(infos, info) - } - slices.SortFunc(infos, func(a, b Info) int { - if a.Category == b.Category { - if a.Name < b.Name { - return -1 - } - if a.Name > b.Name { - return 1 - } - return 0 - } - if a.Category < b.Category { - return -1 - } - return 1 - }) - return infos -} - -func GetTypesMetaIndexed() []Info { - return GetTypesMeta() -} - -func IsKnown(name string) bool { - return NameToType(name) != UnknownType -} diff --git a/pkg/event/metainfo_windows.go b/pkg/event/metainfo_windows.go index ac2819c8f..2fe32a8bd 100644 --- a/pkg/event/metainfo_windows.go +++ b/pkg/event/metainfo_windows.go @@ -19,20 +19,9 @@ package event import ( - "cmp" "slices" ) -// Info describes the event meta info such as human-readable name, category and description. -type Info struct { - // Name is the human-readable representation of the event (e.g. CreateProcess, DeleteFile). - Name string - // Category designates the category to which event pertains. (e.g. process, net) - Category Category - // Description is the short explanation that describes the purpose of the event. - Description string -} - var events = map[Type]Info{ CreateProcess: {"CreateProcess", Process, "Creates a new process and its primary thread"}, TerminateProcess: {"TerminateProcess", Process, "Terminates the process and all of its threads"}, @@ -296,34 +285,6 @@ func NameToTypes(name string) []Type { } } -// GetTypesMeta returns event types metadata. -func GetTypesMeta() []Info { - typs := make([]Info, 0) -outer: - for _, ev := range events { - for _, typ := range typs { - if typ.Name == ev.Name { - continue outer - } - } - typs = append(typs, ev) - } - slices.SortFunc(typs, func(a, b Info) int { - return cmp.Or(cmp.Compare(a.Category, b.Category), cmp.Compare(a.Name, b.Name)) - }) - return typs -} - -// IsKnown indicates if the event type is known given the event name. -func IsKnown(name string) bool { - for _, evt := range GetTypesMeta() { - if evt.Name == name { - return true - } - } - return false -} - // GetTypesMetaIndexed returns indexed event types metadata // that is guaranteed to always return the same event indices. func GetTypesMetaIndexed() []Info { return indexedEvents } diff --git a/pkg/event/param.go b/pkg/event/param.go index ec0a9ba9f..344a2785a 100644 --- a/pkg/event/param.go +++ b/pkg/event/param.go @@ -23,11 +23,11 @@ import ( "net" "reflect" "sort" + "strconv" "strings" "time" "github.com/rabbitstack/fibratus/pkg/util/colorizer" - "github.com/rabbitstack/fibratus/pkg/util/ntstatus" "github.com/rabbitstack/fibratus/pkg/util/va" "golang.org/x/text/cases" "golang.org/x/text/language" @@ -99,6 +99,100 @@ type Param struct { Enum ParamEnum `json:"enum"` } +// NewParam creates a parameter and normalizes its value for the current platform. +func NewParam(name string, typ params.Type, value params.Value, options ...ParamOption) *Param { + var opts paramOpts + for _, opt := range options { + opt(&opts) + } + return &Param{ + Name: name, + Type: typ, + Value: normalizeParamValue(typ, value), + Flags: opts.flags, + Enum: opts.enum, + } +} + +// String returns the string representation of the parameter value. +func (p Param) String() string { + if p.Value == nil { + return "" + } + if value, ok := formatPlatformParam(p); ok { + return value + } + switch p.Type { + case params.Path: + return fmt.Sprintf("%v", p.Value) + case params.Address: + v, ok := p.Value.(uint64) + if !ok { + return "" + } + return va.Address(v).String() + case params.Int8: + return strconv.Itoa(int(p.Value.(int8))) + case params.Uint8: + return strconv.Itoa(int(p.Value.(uint8))) + case params.Int16: + return strconv.Itoa(int(p.Value.(int16))) + case params.Uint16, params.Port: + return strconv.Itoa(int(p.Value.(uint16))) + case params.Uint32: + return strconv.FormatUint(uint64(p.Value.(uint32)), 10) + case params.PID, params.TID: + return formatPlatformID(p.Value) + case params.Int32: + return strconv.Itoa(int(p.Value.(int32))) + case params.Uint64: + return strconv.FormatUint(p.Value.(uint64), 10) + case params.Int64: + return strconv.FormatInt(p.Value.(int64), 10) + case params.IPv4, params.IPv6: + return p.Value.(net.IP).String() + case params.Bool: + return strconv.FormatBool(p.Value.(bool)) + case params.Float: + return strconv.FormatFloat(float64(p.Value.(float32)), 'f', 6, 32) + case params.Double: + return strconv.FormatFloat(p.Value.(float64), 'f', 6, 64) + case params.Time: + return p.Value.(time.Time).String() + case params.Enum: + if p.Enum == nil { + return "" + } + v, ok := p.Value.(uint32) + if !ok { + return "" + } + return p.Enum[v] + case params.Flags, params.Flags64: + if p.Flags == nil { + return "" + } + switch v := p.Value.(type) { + case uint32: + return p.Flags.String(uint64(v)) + case uint64: + return p.Flags.String(v) + default: + return "" + } + case params.Slice: + switch slice := p.Value.(type) { + case []string: + return strings.Join(slice, ",") + default: + return fmt.Sprintf("%v", slice) + } + case params.Binary: + return string(p.Value.([]byte)) + } + return fmt.Sprintf("%v", p.Value) +} + // IsNumber determines if the parameter stores the integer value type. func (p Param) IsNumber() bool { return p.Type == params.Int8 || p.Type == params.Int16 || p.Type == params.Int32 || p.Type == params.Int64 || @@ -111,12 +205,7 @@ func (p Param) IsNumber() bool { // type is converted to string param type, as drive mapping is performed // on the target where the capture is being taken. func (p Param) CaptureType() params.Type { - switch p.Type { - case params.HandleType, params.DOSPath, params.Key: - return params.UnicodeString - default: - return p.Type - } + return captureParamType(p.Type) } // Params is the type that represents the sequence of event parameters @@ -207,83 +296,6 @@ func (pars Params) MustGetString(name string) string { return s } -// GetPid returns the pid from the parameter. -func (pars Params) GetPid() (uint32, error) { - return pars.getPid(params.ProcessID) -} - -// MustGetPid returns the pid parameter. It panics if -// an error occurs while trying to get the pid parameter. -func (pars Params) MustGetPid() uint32 { - pid, err := pars.GetPid() - if err != nil { - panic(err) - } - return pid -} - -// GetPpid returns the parent pid from the parameter. -func (pars Params) GetPpid() (uint32, error) { - return pars.getPid(params.ProcessParentID) -} - -// MustGetPpid returns the parent pid parameter. It panics if -// an error occurs while trying to get the pid parameter. -func (pars Params) MustGetPpid() uint32 { - ppid, err := pars.GetPpid() - if err != nil { - panic(err) - } - return ppid -} - -func (pars Params) getPid(name string) (uint32, error) { - par, err := pars.findParam(name) - if err != nil { - return uint32(0), err - } - if par.Type != params.PID { - return uint32(0), fmt.Errorf("%q parameter is not a PID", name) - } - v, ok := par.Value.(uint32) - if !ok { - return uint32(0), fmt.Errorf("unable to type cast %q parameter to uint32 value from pid", name) - } - return v, nil -} - -// GetTid returns the thread id from the parameter. -func (pars Params) GetTid() (uint32, error) { - par, err := pars.findParam(params.ThreadID) - if err != nil { - return uint32(0), err - } - if par.Type != params.TID { - return uint32(0), fmt.Errorf("%q parameter is not a TID", params.ThreadID) - } - v, ok := par.Value.(uint32) - if !ok { - return uint32(0), fmt.Errorf("unable to type cast %q parameter to uint32 value from tid", params.ThreadID) - } - return v, nil -} - -// MustGetTid returns the thread id from the parameter or panics if an error occurs. -func (pars Params) MustGetTid() uint32 { - par, err := pars.findParam(params.ThreadID) - if err != nil { - panic(err) - } - if par.Type != params.TID { - panic(fmt.Errorf("%q parameter is not a TID", params.ThreadID)) - } - v, ok := par.Value.(uint32) - if !ok { - panic(fmt.Errorf("unable to type cast %q parameter to uint32 value from tid", params.ThreadID)) - } - return v -} - // GetUint8 returns the underlying uint8 value from the parameter. func (pars Params) GetUint8(name string) (uint8, error) { par, err := pars.findParam(name) @@ -737,18 +749,13 @@ func (pars Params) Colorize() string { // color applies a semantic colour to a single parameter value based // on its type and for string types its content. func (p *Param) color() string { + if color, ok := platformParamColor(p); ok { + return color + } switch p.Type { case params.Address: return colorizer.SpanDim(colorizer.Span(colorizer.Gray, "0x"+p.String())) - case params.Status: - v := p.String() - - if v == ntstatus.Success { - return colorizer.Span(colorizer.Green, v) - } - return colorizer.Span(colorizer.Red, v) - case params.Int8, params.Int16, params.Int32, params.Int64, params.Uint8, params.Uint16, params.Uint32, params.Uint64, params.Float, params.Double: @@ -764,9 +771,6 @@ func (p *Param) color() string { } return colorizer.Span(colorizer.Coral, p.String()) - case params.UnicodeString, params.AnsiString, params.SID: - return colorizer.Span(colorizer.White, p.String()) - case params.IPv4, params.IPv6: return colorizer.Span(colorizer.Blue, p.String()) diff --git a/pkg/event/param_capture_windows.go b/pkg/event/param_capture_windows.go deleted file mode 100644 index d8c79be40..000000000 --- a/pkg/event/param_capture_windows.go +++ /dev/null @@ -1,76 +0,0 @@ -//go:build windows - -/* - * Copyright 2019-2020 by Nedim Sabic Sabic - * Copyright 2026 by Mostafa Moradian - * https://www.fibratus.io - * All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package event - -import ( - "github.com/rabbitstack/fibratus/pkg/event/params" - "github.com/rabbitstack/fibratus/pkg/fs" - "github.com/rabbitstack/fibratus/pkg/network" - "github.com/rabbitstack/fibratus/pkg/util/key" -) - -// NewParamFromCapture builds a parameter instance from the restored capture state. -func NewParamFromCapture(name string, typ params.Type, value params.Value, etype Type) *Param { - var enum ParamEnum - var flags ParamFlags - switch name { - case params.FileOperation: - enum = fs.FileCreateDispositions - case params.FileCreateOptions: - flags = FileCreateOptionsFlags - case params.FileAttributes: - flags = FileAttributeFlags - case params.FileShareMask: - flags = FileShareModeFlags - case params.FileInfoClass: - enum = fs.FileInfoClasses - case params.FileType: - enum = fs.FileTypes - case params.NetL4Proto: - enum = network.ProtoNames - case params.RegValueType: - enum = key.RegistryValueTypes - case params.MemAllocType: - flags = MemAllocationFlags - case params.FileViewSectionType: - enum = ViewSectionTypes - case params.DNSOpts: - flags = DNSOptsFlags - case params.DNSRR: - enum = DNSRecordTypes - case params.DNSRcode: - enum = DNSResponseCodes - case params.DesiredAccess: - if etype == OpenProcess { - flags = PsAccessRightFlags - } else { - flags = ThreadAccessRightFlags - } - case params.MemProtect: - if etype == VirtualAlloc || etype == VirtualFree { - flags = MemProtectionFlags - } else { - flags = ViewProtectionFlags - } - } - return &Param{Name: name, Type: typ, Value: value, Enum: enum, Flags: flags} -} diff --git a/pkg/event/param_linux.go b/pkg/event/param_linux.go index af0a2ce89..761a72143 100644 --- a/pkg/event/param_linux.go +++ b/pkg/event/param_linux.go @@ -22,104 +22,103 @@ package event import ( "fmt" - "net" "strconv" - "strings" - "time" "github.com/rabbitstack/fibratus/pkg/event/params" - "github.com/rabbitstack/fibratus/pkg/util/ntstatus" - "github.com/rabbitstack/fibratus/pkg/util/va" + "github.com/rabbitstack/fibratus/pkg/util/colorizer" ) -// NewParam creates a new event parameter. -func NewParam(name string, typ params.Type, value params.Value, options ...ParamOption) *Param { - var opts paramOpts - for _, opt := range options { - opt(&opts) +func normalizeParamValue(_ params.Type, value params.Value) params.Value { return value } + +func formatPlatformParam(p Param) (string, bool) { + if p.Type != params.String { + return "", false + } + value, ok := p.Value.(string) + if !ok { + return fmt.Sprintf("%v", p.Value), true } - return &Param{Name: name, Type: typ, Value: value, Flags: opts.flags, Enum: opts.enum} + return value, true } -// String returns the string representation of the parameter value. -func (p Param) String() string { - if p.Value == nil { - return "" - } +func formatPlatformID(value params.Value) string { + return strconv.FormatUint(value.(uint64), 10) +} + +func captureParamType(typ params.Type) params.Type { return typ } + +func platformParamColor(p *Param) (string, bool) { switch p.Type { - case params.UnicodeString, params.AnsiString, params.Path, params.DOSPath, params.Key, params.HandleType: - if s, ok := p.Value.(string); ok { - return s - } - return fmt.Sprintf("%v", p.Value) + case params.String: + return colorizer.Span(colorizer.White, p.String()), true case params.Status: - v, ok := p.Value.(uint32) - if !ok { - return "" - } - return ntstatus.FormatMessage(v) - case params.Address: - v, ok := p.Value.(uint64) - if !ok { - return "" - } - return va.Address(v).String() - case params.Int8: - return strconv.Itoa(int(p.Value.(int8))) - case params.Uint8: - return strconv.Itoa(int(p.Value.(uint8))) - case params.Int16: - return strconv.Itoa(int(p.Value.(int16))) - case params.Uint16, params.Port: - return strconv.Itoa(int(p.Value.(uint16))) - case params.Uint32, params.PID, params.TID: - return strconv.Itoa(int(p.Value.(uint32))) - case params.Int32: - return strconv.Itoa(int(p.Value.(int32))) - case params.Uint64: - return strconv.FormatUint(p.Value.(uint64), 10) - case params.Int64: - return strconv.Itoa(int(p.Value.(int64))) - case params.IPv4, params.IPv6: - return p.Value.(net.IP).String() - case params.Bool: - return strconv.FormatBool(p.Value.(bool)) - case params.Float: - return strconv.FormatFloat(float64(p.Value.(float32)), 'f', 6, 32) - case params.Double: - return strconv.FormatFloat(p.Value.(float64), 'f', 6, 64) - case params.Time: - return p.Value.(time.Time).String() - case params.Enum: - if p.Enum == nil { - return "" + if p.String() == "0" { + return colorizer.Span(colorizer.Green, p.String()), true } - v, ok := p.Value.(uint32) - if !ok { - return "" - } - return p.Enum[v] - case params.Flags, params.Flags64: - if p.Flags == nil { - return "" - } - switch v := p.Value.(type) { - case uint32: - return p.Flags.String(uint64(v)) - case uint64: - return p.Flags.String(v) - default: - return "" - } - case params.Slice: - switch slice := p.Value.(type) { - case []string: - return strings.Join(slice, ",") - default: - return fmt.Sprintf("%v", slice) - } - case params.Binary: - return string(p.Value.([]byte)) + return colorizer.Span(colorizer.Red, p.String()), true + default: + return "", false + } +} + +// NewParamFromCapture builds a parameter from restored capture state. +func NewParamFromCapture(name string, typ params.Type, value params.Value, _ Type) *Param { + return &Param{Name: name, Type: typ, Value: value} +} + +// GetPid returns the process identifier. +func (pars Params) GetPid() (uint64, error) { + return pars.getID(params.ProcessID, params.PID) +} + +// MustGetPid returns the process identifier or panics. +func (pars Params) MustGetPid() uint64 { + id, err := pars.GetPid() + if err != nil { + panic(err) + } + return id +} + +// GetPpid returns the parent process identifier. +func (pars Params) GetPpid() (uint64, error) { + return pars.getID(params.ProcessParentID, params.PID) +} + +// MustGetPpid returns the parent process identifier or panics. +func (pars Params) MustGetPpid() uint64 { + id, err := pars.GetPpid() + if err != nil { + panic(err) + } + return id +} + +// GetTid returns the thread identifier. +func (pars Params) GetTid() (uint64, error) { + return pars.getID(params.ThreadID, params.TID) +} + +// MustGetTid returns the thread identifier or panics. +func (pars Params) MustGetTid() uint64 { + id, err := pars.GetTid() + if err != nil { + panic(err) + } + return id +} + +func (pars Params) getID(name string, typ params.Type) (uint64, error) { + param, err := pars.findParam(name) + if err != nil { + return 0, err + } + if param.Type != typ { + return 0, fmt.Errorf("%q parameter has unexpected identifier type", name) + } + value, ok := param.Value.(uint64) + if !ok { + return 0, fmt.Errorf("unable to type cast %q parameter to uint64 identifier", name) } - return fmt.Sprintf("%v", p.Value) + return value, nil } diff --git a/pkg/event/param_test.go b/pkg/event/param_test.go index a47b18dcb..059687f99 100644 --- a/pkg/event/param_test.go +++ b/pkg/event/param_test.go @@ -19,27 +19,28 @@ package event import ( + "testing" + "github.com/rabbitstack/fibratus/pkg/event/params" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "testing" ) func TestParams(t *testing.T) { pars := Params{ - params.FileObject: {Name: params.FileObject, Type: params.Uint64, Value: uint64(18446738026482168384)}, - params.ThreadID: {Name: params.ThreadID, Type: params.Uint32, Value: uint32(1484)}, - params.FileCreateOptions: {Name: params.FileCreateOptions, Type: params.Uint32, Value: uint32(1223456)}, - params.FilePath: {Name: params.FilePath, Type: params.UnicodeString, Value: "\\Device\\HarddiskVolume2\\Windows\\system32\\kernel32.dll"}, - params.FileShareMask: {Name: params.FileShareMask, Type: params.Uint32, Value: uint32(5)}, + params.FileObject: {Name: params.FileObject, Type: params.Uint64, Value: uint64(18446738026482168384)}, + params.ThreadID: {Name: params.ThreadID, Type: params.Uint32, Value: uint32(1484)}, + params.FileOffset: {Name: params.FileOffset, Type: params.Uint64, Value: uint64(1223456)}, + params.FilePath: {Name: params.FilePath, Type: params.Path, Value: "/usr/bin/bash"}, + params.ProcessID: {Name: params.ProcessID, Type: params.Uint32, Value: uint32(5)}, } assert.True(t, pars.Contains(params.FileObject)) - assert.False(t, pars.Contains(params.FileOffset)) + assert.False(t, pars.Contains(params.ProcessName)) filename, err := pars.GetString(params.FilePath) require.NoError(t, err) - assert.Equal(t, "\\Device\\HarddiskVolume2\\Windows\\system32\\kernel32.dll", filename) + assert.Equal(t, "/usr/bin/bash", filename) _, err = pars.GetString(params.FileObject) require.Error(t, err) @@ -51,10 +52,10 @@ func TestParams(t *testing.T) { assert.False(t, pars.Contains(params.ThreadID)) assert.Equal(t, 4, pars.Len()) - require.NoError(t, pars.Set(params.FileShareMask, uint32(5), params.Enum)) + require.NoError(t, pars.Set(params.ProcessID, uint32(5), params.Enum)) - require.NoError(t, pars.SetValue(params.FilePath, "\\Device\\HarddiskVolume2\\Windows\\system32\\KERNEL32.dll")) + require.NoError(t, pars.SetValue(params.FilePath, "/usr/bin/zsh")) filename1, err := pars.GetString(params.FilePath) require.NoError(t, err) - assert.Equal(t, "\\Device\\HarddiskVolume2\\Windows\\system32\\KERNEL32.dll", filename1) + assert.Equal(t, "/usr/bin/zsh", filename1) } diff --git a/pkg/event/param_windows.go b/pkg/event/param_windows.go index 2025461e0..12d89bda4 100644 --- a/pkg/event/param_windows.go +++ b/pkg/event/param_windows.go @@ -21,162 +21,213 @@ package event import ( "expvar" "fmt" - "net" "strconv" - "strings" - "time" "unsafe" "github.com/rabbitstack/fibratus/pkg/event/params" "github.com/rabbitstack/fibratus/pkg/fs" htypes "github.com/rabbitstack/fibratus/pkg/handle/types" + "github.com/rabbitstack/fibratus/pkg/network" "github.com/rabbitstack/fibratus/pkg/sys" "github.com/rabbitstack/fibratus/pkg/sys/etw" + "github.com/rabbitstack/fibratus/pkg/util/colorizer" "github.com/rabbitstack/fibratus/pkg/util/ip" "github.com/rabbitstack/fibratus/pkg/util/key" "github.com/rabbitstack/fibratus/pkg/util/ntstatus" - "github.com/rabbitstack/fibratus/pkg/util/va" "golang.org/x/sys/windows" ) -// unknownKeysCount counts the number of times the registry key failed to convert from native format var unknownKeysCount = expvar.NewInt("registry.unknown.keys.count") -// NewParam creates a new event parameter. Since the parameter type is already categorized, -// we can coerce the value to the appropriate representation (e.g. hex, IP address) -func NewParam(name string, typ params.Type, value params.Value, options ...ParamOption) *Param { - var opts paramOpts - for _, opt := range options { - opt(&opts) - } - var v params.Value +func normalizeParamValue(typ params.Type, value params.Value) params.Value { switch typ { case params.IPv4: - v = ip.ToIPv4(value.(uint32)) + return ip.ToIPv4(value.(uint32)) case params.IPv6: - v = ip.ToIPv6(value.([]byte)) + return ip.ToIPv6(value.([]byte)) case params.Port: - v = windows.Ntohs(value.(uint16)) + return windows.Ntohs(value.(uint16)) default: - v = value + return value } - return &Param{Name: name, Type: typ, Value: v, Flags: opts.flags, Enum: opts.enum} } -// String returns the string representation of the parameter value. -func (p Param) String() string { - if p.Value == nil { - return "" - } +func formatPlatformParam(p Param) (string, bool) { switch p.Type { case params.UnicodeString, params.AnsiString, params.Path: - return p.Value.(string) + return p.Value.(string), true case params.SID, params.WbemSID: sid, err := getSID(&p) if err != nil { - return "" + return "", true } if p.Name == params.ProcessTokenIntegrityLevel { - return sys.RidToString(sid) + return sys.RidToString(sid), true } - return sid.String() + return sid.String(), true case params.DOSPath: - return fs.GetDevMapper().Convert(p.Value.(string)) + return fs.GetDevMapper().Convert(p.Value.(string)), true case params.Key: rootKey, keyName := key.Format(p.Value.(string)) if keyName != "" && rootKey != key.Invalid { - return rootKey.String() + "\\" + keyName + return rootKey.String() + "\\" + keyName, true } if rootKey != key.Invalid { - return rootKey.String() + return rootKey.String(), true } unknownKeysCount.Add(1) - return keyName + return keyName, true case params.HandleType: - return htypes.ConvertTypeIDToName(p.Value.(uint16)) + return htypes.ConvertTypeIDToName(p.Value.(uint16)), true case params.Status: - v, ok := p.Value.(uint32) - if !ok { - return "" - } - return ntstatus.FormatMessage(v) - case params.Address: - v, ok := p.Value.(uint64) - if !ok { - return "" - } - return va.Address(v).String() - case params.Int8: - return strconv.Itoa(int(p.Value.(int8))) - case params.Uint8: - return strconv.Itoa(int(p.Value.(uint8))) - case params.Int16: - return strconv.Itoa(int(p.Value.(int16))) - case params.Uint16, params.Port: - return strconv.Itoa(int(p.Value.(uint16))) - case params.Uint32, params.PID, params.TID: - return strconv.Itoa(int(p.Value.(uint32))) - case params.Int32: - return strconv.Itoa(int(p.Value.(int32))) - case params.Uint64: - return strconv.FormatUint(p.Value.(uint64), 10) - case params.Int64: - return strconv.Itoa(int(p.Value.(int64))) - case params.IPv4, params.IPv6: - return p.Value.(net.IP).String() - case params.Bool: - return strconv.FormatBool(p.Value.(bool)) - case params.Float: - return strconv.FormatFloat(float64(p.Value.(float32)), 'f', 6, 32) - case params.Double: - return strconv.FormatFloat(p.Value.(float64), 'f', 6, 64) - case params.Time: - return p.Value.(time.Time).String() - case params.Enum: - if p.Enum == nil { - return "" - } - e := p.Value - v, ok := e.(uint32) + value, ok := p.Value.(uint32) if !ok { - return "" + return "", true } - return p.Enum[v] - case params.Flags, params.Flags64: - if p.Flags == nil { - return "" + return ntstatus.FormatMessage(value), true + default: + return "", false + } +} + +func formatPlatformID(value params.Value) string { + return strconv.FormatUint(uint64(value.(uint32)), 10) +} + +func captureParamType(typ params.Type) params.Type { + switch typ { + case params.HandleType, params.DOSPath, params.Key: + return params.UnicodeString + default: + return typ + } +} + +func platformParamColor(p *Param) (string, bool) { + switch p.Type { + case params.UnicodeString, params.AnsiString, params.SID: + return colorizer.Span(colorizer.White, p.String()), true + case params.Status: + if p.String() == ntstatus.Success { + return colorizer.Span(colorizer.Green, p.String()), true } - f := p.Value - switch v := f.(type) { - case uint32: - return p.Flags.String(uint64(v)) - case uint64: - return p.Flags.String(v) - default: - return "" + return colorizer.Span(colorizer.Red, p.String()), true + default: + return "", false + } +} + +// NewParamFromCapture builds a parameter from restored capture state. +func NewParamFromCapture(name string, typ params.Type, value params.Value, etype Type) *Param { + var enum ParamEnum + var flags ParamFlags + switch name { + case params.FileOperation: + enum = fs.FileCreateDispositions + case params.FileCreateOptions: + flags = FileCreateOptionsFlags + case params.FileAttributes: + flags = FileAttributeFlags + case params.FileShareMask: + flags = FileShareModeFlags + case params.FileInfoClass: + enum = fs.FileInfoClasses + case params.FileType: + enum = fs.FileTypes + case params.NetL4Proto: + enum = network.ProtoNames + case params.RegValueType: + enum = key.RegistryValueTypes + case params.MemAllocType: + flags = MemAllocationFlags + case params.FileViewSectionType: + enum = ViewSectionTypes + case params.DNSOpts: + flags = DNSOptsFlags + case params.DNSRR: + enum = DNSRecordTypes + case params.DNSRcode: + enum = DNSResponseCodes + case params.DesiredAccess: + if etype == OpenProcess { + flags = PsAccessRightFlags + } else { + flags = ThreadAccessRightFlags } - case params.Slice: - switch slice := p.Value.(type) { - case []string: - return strings.Join(slice, ",") - default: - return fmt.Sprintf("%v", slice) + case params.MemProtect: + if etype == VirtualAlloc || etype == VirtualFree { + flags = MemProtectionFlags + } else { + flags = ViewProtectionFlags } - case params.Binary: - return string(p.Value.([]byte)) } - return fmt.Sprintf("%v", p.Value) + return &Param{Name: name, Type: typ, Value: value, Enum: enum, Flags: flags} +} + +// GetPid returns the process identifier. +func (pars Params) GetPid() (uint32, error) { + return pars.getID(params.ProcessID, params.PID) +} + +// MustGetPid returns the process identifier or panics. +func (pars Params) MustGetPid() uint32 { + id, err := pars.GetPid() + if err != nil { + panic(err) + } + return id +} + +// GetPpid returns the parent process identifier. +func (pars Params) GetPpid() (uint32, error) { + return pars.getID(params.ProcessParentID, params.PID) +} + +// MustGetPpid returns the parent process identifier or panics. +func (pars Params) MustGetPpid() uint32 { + id, err := pars.GetPpid() + if err != nil { + panic(err) + } + return id +} + +// GetTid returns the thread identifier. +func (pars Params) GetTid() (uint32, error) { + return pars.getID(params.ThreadID, params.TID) +} + +// MustGetTid returns the thread identifier or panics. +func (pars Params) MustGetTid() uint32 { + id, err := pars.GetTid() + if err != nil { + panic(err) + } + return id +} + +func (pars Params) getID(name string, typ params.Type) (uint32, error) { + param, err := pars.findParam(name) + if err != nil { + return 0, err + } + if param.Type != typ { + return 0, fmt.Errorf("%q parameter has unexpected identifier type", name) + } + value, ok := param.Value.(uint32) + if !ok { + return 0, fmt.Errorf("unable to type cast %q parameter to uint32 identifier", name) + } + return value, nil } -// GetSID returns the raw SID (Security Identifier) parameter as -// typed representation on which various operations can be performed, -// such as converting the SID to string or resolving username/domain. +// GetSID returns the raw Windows security identifier parameter. func (pars Params) GetSID() (*windows.SID, error) { - par, err := pars.findParam(params.UserSID) + param, err := pars.findParam(params.UserSID) if err != nil { return nil, err } - return getSID(par) + return getSID(param) } func getSID(param *Param) (*windows.SID, error) { @@ -187,17 +238,14 @@ func getSID(param *Param) (*windows.SID, error) { if sid == nil { return nil, fmt.Errorf("sid linked to parameter %s is empty", param.Name) } - b := uintptr(unsafe.Pointer(&sid[0])) + pointer := uintptr(unsafe.Pointer(&sid[0])) if param.Type == params.WbemSID { - // a WBEM SID is actually a TOKEN_USER structure followed - // by the SID, so we have to double the pointer size - b += uintptr(8 * 2) + pointer += uintptr(8 * 2) } - return (*windows.SID)(unsafe.Pointer(b)), nil + return (*windows.SID)(unsafe.Pointer(pointer)), nil } -// MustGetSID returns the SID (Security Identifier) event parameter -// or panics if an error occurs. +// MustGetSID returns the Windows security identifier or panics. func (pars Params) MustGetSID() *windows.SID { sid, err := pars.GetSID() if err != nil { @@ -208,10 +256,6 @@ func (pars Params) MustGetSID() *windows.SID { var paramDecoder = &ParamDecoder{} -// decodeParams parses the event binary layout to extract -// the parameters. Each event is annotated with the schema -// version number which helps us determine when the event -// schema changes in order to parse new fields. func (e *Event) decodeParams(r *etw.EventRecord) { switch r.Header.ProviderID { case RegistryEventGUID: diff --git a/pkg/event/params/names.go b/pkg/event/params/names.go index cb269f02c..153a8d14f 100644 --- a/pkg/event/params/names.go +++ b/pkg/event/params/names.go @@ -19,122 +19,54 @@ package params const ( - // NTStatus is the parameter that identifies the NTSTATUS value. - NTStatus = "status" - // ProcessID represents the process identifier. ProcessID = "pid" // TargetProcessID represents the target process identifier. TargetProcessID = "target_pid" - // ProcessObject field represents the address of the process object in the kernel. - ProcessObject = "kproc" // ThreadID field represents the thread identifier. ThreadID = "tid" - // Callstack field represents the thread callstack. - Callstack = "callstack" - // CallstackTimestamp field identifvies the callstack timestamp parameter. - CallstackTimestamp = "callstack_timestamp" // ProcessParentID field represents the parent process identifier. ProcessParentID = "ppid" - // ProcessRealParentID field presents the real parent process identifier. - ProcessRealParentID = "real_ppid" // SessionID fields represents the session identifier. SessionID = "session_id" - // UserSID field is the security identifier associated to the process token under which it is run. - UserSID = "sid" // Username field represents the username under which the event was generated. Username = "username" - // Domain field represents the domain under which the event was generated. - Domain = "domain" // ProcessName field denotes the process Module name. ProcessName = "name" // Exe field denotes the full path of the executable. Exe = "exe" // Cmdline field represents the process command line. Cmdline = "cmdline" - // DTB field denotes the address of the process directory table. - DTB = "directory_table_base" // ProcessFlags field denotes the process creation flags ProcessFlags = "flags" // ExitStatus is the field that represents the process exit status. ExitStatus = "exit_status" // StartTime field denotes the process start time. StartTime = "start_time" - // ProcessTokenIntegrityLevel field denotes the process integrity level. - ProcessTokenIntegrityLevel = "token_integrity_level" - // ProcessTokenElevationType field designates the process token elevation type. - ProcessTokenElevationType = "token_elevation_type" - // ProcessTokenIsElevated field designates if the process token is elevated. - ProcessTokenIsElevated = "token_is_elevated" - - // DesiredAccess field denotes the access rights for different kernel objects such as processes or threads. - DesiredAccess = "desired_access" - - // BasePrio field is the thread base priority assigned by the scheduler. - BasePrio = "base_prio" - // IOPrio represents the filed that indicates the thread I/O priority. - IOPrio = "io_prio" - // PagePrio field denotes page priority. - PagePrio = "page_prio" - // KstackBase field is the start address of the kernel space stack. - KstackBase = "kstack" - // KstackLimit field is the end address of the kernel space stack. - KstackLimit = "kstack_limit" - // UstackBase field is the start address of the user space stack. - UstackBase = "ustack" - // UstackLimit field is the end address of the user space stack. - UstackLimit = "ustack_limit" - // StartAddress field is the thread start address. - StartAddress = "start_address" - // StartAddressSymbol field is the symbol associated with the thread start address. - StartAddressSymbol = "start_address_symbol" - // StartAddressModule field is the module where the thread start address is mapped. - StartAddressModule = "start_address_module" - // TEB field is the address of the Thread Environment Block (TEB) - TEB = "teb" - // FileObject determines the field name for the file object pointer. FileObject = "file_object" // FilePath represents the field that designates the absolute path of the file. FilePath = "file_path" - // FileCreateOptions is the field that represents the values passed in the CreateDispositions parameter to the NtCreateFile function. - FileCreateOptions = "create_options" - // FileOperation is the field that represents the values passed in the CreateOptions parameter to the NtCreateFile function. - FileOperation = "create_disposition" // FileCreated represents the name for the file creation field. FileCreated = "created" // FileAccessed represents the name for the file access field. FileAccessed = "accessed" // FileModified represents the name for the file modification field. FileModified = "modified" - // FileShareMask represents the field name for the share access mask. - FileShareMask = "share_mask" // FileType represents the field name that indicates the file type. FileType = "type" - // FileAttributes is the field that represents file attribute values. - FileAttributes = "attributes" // FileIoSize is the filed that represents the number of bytes in file read/write operations. FileIoSize = "io_size" // FileOffset represents the file for the file offset in read/write operations. FileOffset = "offset" - // FileInfoClass represents the file information class. - FileInfoClass = "class" // FileKey represents the directory key identifier in EnumDirectory events. FileKey = "file_key" // FileDirectory represents the field for the directory name in EnumDirectory events. FileDirectory = "directory" - // FileIrpPtr represents the I/O request packet id. - FileIrpPtr = "irp" // FileExtraInfo is the parameter that represents extra information returned by the file system for the operation. For example for a read request, the actual number of bytes that were read. FileExtraInfo = "extra_info" - // FileIsDLL is the parameter that indicates if the file is a DLL - FileIsDLL = "is_dll" - // FileIsDriver is the parameter that indicates if the file is a driver - FileIsDriver = "is_driver" // FileIsExecutable is the parameter that indicates if the file is an executable FileIsExecutable = "is_exec" - // FileIsDotnet is the parameter that indicates if the file is a .NET assembly - FileIsDotnet = "is_dotnet" // FileViewBase is the parameter that represents the base address of the mapped section. FileViewBase = "view_base" @@ -143,47 +75,12 @@ const ( // FileViewSectionType is the parameter that represents the mapped section type. FileViewSectionType = "section_type" - // RegKeyHandle identifies the parameter name for the registry key handle. - RegKeyHandle = "key_handle" - // RegKCB identifies the parameter name for the registry key control block. - RegKCB = "kcb" - // RegPath represents the parameter name for the fully qualified key path. - RegPath = "key_path" - // RegValue identifies the parameter name that contains the value - RegValue = "value" - // RegValueType identifies the parameter that represents registry value type e.g (DWORD, BINARY) - RegValueType = "value_type" - // RegData identifies the parameter that stores the captured registry data - RegData = "data" - // ModuleBase identifies the parameter name for the base address of the process in which the Mmdule is loaded. ModuleBase = "base_address" // ModuleSize represents the parameter name for the size of the module in bytes. ModuleSize = "module_size" - // ModuleCheckSum is the parameter name for module checksum. - ModuleCheckSum = "checksum" - // ModuleTimeDateStamp is the parametter name for module timedate stamp. - ModuleTimeDateStamp = "timedate_stamp" - // ModuleDefaultBase is the parameter name that represents module's base address. - ModuleDefaultBase = "default_address" // ModulePath is the parameter name that denotes the file path and extension of the DLL/executable Module. ModulePath = "file_path" - // ModuleSignatureLevel is the parameter denoting the loaded module signature level. - ModuleSignatureLevel = "signature_level" - // ModuleSignatureType is the parameter denoting the loaded module signature type. - ModuleSignatureType = "signature_type" - // ModuleCertSubject is the parameter that indicates the subject of the certificate is the entity its public key is associated with. - ModuleCertSubject = "cert_subject" - // ModuleCertIssuer is the parameter that represents the certificate authority (CA). - ModuleCertIssuer = "cert_issuer" - // ModuleCertSerial is the parameter that represents the serial number MUST be a positive integer assigned - // by the CA to each certificate. - ModuleCertSerial = "cert_serial" - // ModuleCertNotBefore is the parameter that specifies the certificate won't be valid before this timestamp. - ModuleCertNotBefore = "cert_not_before" - // ModuleCertNotAfter is the parameter that specifies the certificate won't be valid after this timestamp. - ModuleCertNotAfter = "cert_not_after" - // NetSize identifies the parameter name that represents the packet size. NetSize = "size" // NetDIP is the parameter name that denotes the destination IP address. @@ -238,17 +135,6 @@ const ( // DNSAnswers is the field that represents DNS response answers DNSAnswers = "answers" - // HandleID identifies the parameter that specifies the handle identifier. - HandleID = "handle_id" - // HandleSourceID identifies the parameter that specifies the source handle identifier. - HandleSourceID = "handle_source_id" - // HandleObject identifies the parameter that represents the kernel object to which handle is associated. - HandleObject = "handle_object" - // HandleObjectName identifies the parameter that represents the kernel object name. - HandleObjectName = "handle_name" - // HandleObjectTypeID identifies the parameter that represents the kernel object type identifier. - HandleObjectTypeID = "type_id" - // MemBaseAddress identifies the parameter that denotes the allocation base address. MemBaseAddress = "base_address" // MemRegionSize identifies the parameter that represents the allocated region size. @@ -266,37 +152,4 @@ const ( LinkSource = "source" // LinkTarget identifies the parameter that represents the target symbolic link object or other kernel object LinkTarget = "target" - - // ThreadpoolPoolID represents the thread pool identifier. - ThreadpoolPoolID = "pool_id" - // ThreadpoolTaskID represents the thread pool task identifier. - ThreadpoolTaskID = "task_id" - // ThreadpoolCallback represents the address of the callback function. - ThreadpoolCallback = "callback" - // ThreadpoolCallbackSymbol represents the callback symbol. - ThreadpoolCallbackSymbol = "callback_symbol" - // ThreadpoolCallbackModule represents the module containing the callback symbol. - ThreadpoolCallbackModule = "callback_module" - // ThreadpoolContext represents the address of the callback context. - ThreadpoolContext = "context" - // ThreadpoolContextRip represents the value of instruction pointer contained in the callback context. - ThreadpoolContextRip = "context_rip" - // ThreadpoolContextRipSymbol represents the symbol name associated with the instruction pointer in callback context. - ThreadpoolContextRipSymbol = "context_rip_symbol" - // ThreadpoolContextRipModule represents the module name associated with the instruction pointer in callback context. - ThreadpoolContextRipModule = "context_rip_module" - // ThreadpoolSubprocessTag represents the service identifier associated with the thread pool. - ThreadpoolSubprocessTag = "subprocess_tag" - // ThreadpoolTimerDuetime represents the timer due time. - ThreadpoolTimerDuetime = "duetime" - // ThreadpoolTimerSubqueue represents the memory address of the timer subqueue. - ThreadpoolTimerSubqueue = "subqueue" - // ThreadpoolTimer represents the memory address of the timer object. - ThreadpoolTimer = "timer" - // ThreadpoolTimerPeriod represents the period of the timer - ThreadpoolTimerPeriod = "period" - // ThreadpoolTimerWindow represents the timer tolerate period. - ThreadpoolTimerWindow = "window" - // ThreadpoolTimerAbsolute indicates if the timer is absolute or relative. - ThreadpoolTimerAbsolute = "absolute" ) diff --git a/pkg/event/params/names_linux.go b/pkg/event/params/names_linux.go new file mode 100644 index 000000000..4d5acd049 --- /dev/null +++ b/pkg/event/params/names_linux.go @@ -0,0 +1,30 @@ +//go:build linux + +/* + * Copyright 2026 by Mostafa Moradian + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package params + +const ( + // CloneFlags is the bitmask supplied to clone(2). + CloneFlags = "clone_flags" + // UID is the effective Linux user identifier. + UID = "uid" + // GID is the effective Linux group identifier. + GID = "gid" +) diff --git a/pkg/event/params/names_windows.go b/pkg/event/params/names_windows.go new file mode 100644 index 000000000..a457c1e10 --- /dev/null +++ b/pkg/event/params/names_windows.go @@ -0,0 +1,91 @@ +/* + * Copyright 2019-2020 by Nedim Sabic Sabic + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package params + +const ( + NTStatus = "status" + ProcessObject = "kproc" + Callstack = "callstack" + CallstackTimestamp = "callstack_timestamp" + ProcessRealParentID = "real_ppid" + UserSID = "sid" + Domain = "domain" + DTB = "directory_table_base" + ProcessTokenIntegrityLevel = "token_integrity_level" + ProcessTokenElevationType = "token_elevation_type" + ProcessTokenIsElevated = "token_is_elevated" + DesiredAccess = "desired_access" + BasePrio = "base_prio" + IOPrio = "io_prio" + PagePrio = "page_prio" + KstackBase = "kstack" + KstackLimit = "kstack_limit" + UstackBase = "ustack" + UstackLimit = "ustack_limit" + StartAddress = "start_address" + StartAddressSymbol = "start_address_symbol" + StartAddressModule = "start_address_module" + TEB = "teb" + FileCreateOptions = "create_options" + FileOperation = "create_disposition" + FileShareMask = "share_mask" + FileAttributes = "attributes" + FileInfoClass = "class" + FileIrpPtr = "irp" + FileIsDLL = "is_dll" + FileIsDriver = "is_driver" + FileIsDotnet = "is_dotnet" + RegKeyHandle = "key_handle" + RegKCB = "kcb" + RegPath = "key_path" + RegValue = "value" + RegValueType = "value_type" + RegData = "data" + ModuleCheckSum = "checksum" + ModuleTimeDateStamp = "timedate_stamp" + ModuleDefaultBase = "default_address" + ModuleSignatureLevel = "signature_level" + ModuleSignatureType = "signature_type" + ModuleCertSubject = "cert_subject" + ModuleCertIssuer = "cert_issuer" + ModuleCertSerial = "cert_serial" + ModuleCertNotBefore = "cert_not_before" + ModuleCertNotAfter = "cert_not_after" + HandleID = "handle_id" + HandleSourceID = "handle_source_id" + HandleObject = "handle_object" + HandleObjectName = "handle_name" + HandleObjectTypeID = "type_id" + ThreadpoolPoolID = "pool_id" + ThreadpoolTaskID = "task_id" + ThreadpoolCallback = "callback" + ThreadpoolCallbackSymbol = "callback_symbol" + ThreadpoolCallbackModule = "callback_module" + ThreadpoolContext = "context" + ThreadpoolContextRip = "context_rip" + ThreadpoolContextRipSymbol = "context_rip_symbol" + ThreadpoolContextRipModule = "context_rip_module" + ThreadpoolSubprocessTag = "subprocess_tag" + ThreadpoolTimerDuetime = "duetime" + ThreadpoolTimerSubqueue = "subqueue" + ThreadpoolTimer = "timer" + ThreadpoolTimerPeriod = "period" + ThreadpoolTimerWindow = "window" + ThreadpoolTimerAbsolute = "absolute" +) diff --git a/pkg/event/params/param_types.go b/pkg/event/params/param_types.go index aec8c363d..094ff92f2 100644 --- a/pkg/event/params/param_types.go +++ b/pkg/event/params/param_types.go @@ -18,96 +18,47 @@ package params -// Type defines event parameter type +// Type defines an event parameter type. type Type uint16 const ( - // Null is a null parameter type - Null Type = iota - // UnicodeString a string of 16-bit characters. By default, assumed to have been encoded using UTF-16LE - UnicodeString - // AnsiString a string of 8-bit characters - AnsiString - // Int8 a signed 8-bit integer - Int8 - // Uint8 an unsigned 8-bit integer - Uint8 - // Int16 a signed 16-bit integer - Int16 - // Uint16 an unsigned 16-bit integer - Uint16 - // Int32 a signed 32-bit integer - Int32 - // Uint32 an unsigned 32-bit integer - Uint32 - // Int64 a signed 64-bit integer - Int64 - // Uint64 an unsigned 64-bit integer - Uint64 - // Float an IEEE 4-byte floating-point number - Float - // Double an IEEE 8-byte floating-point number - Double - // Bool a 32-bit value where 0 is false and 1 is true - Bool - // Binary is a binary data of variable size. The size must be specified in the data definition as a constant or a reference to another (integer) data item.For an IP V6 address, the data should be an IN6_ADDR structure. - // For a socket address, the data should be a SOCKADDR_STORAGE structure. The AF_INET, AF_INET6, and AF_LINK address families are supported - Binary - // GUID is a GUID structure. On output, the GUID is rendered in the registry string form, {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} - GUID - // Pointer an unsigned 32-bit or 64-bit pointer value. The size depends on the architecture of the computer logging the event - Pointer - // SID a security identifier (SID) structure that uniquely identifies a user or group - SID - // PID is the process identifier - PID - // TID is the thread identifier - TID - // WbemSID is the Web-Based Enterprise Management security identifier. - WbemSID - // Port represents the endpoint port number - Port - // IP is the IP address - IP - // IPv4 is the IPv4 address - IPv4 - // IPv6 is the IPv6 address - IPv6 - // Time represents the timestamp - Time - // Slice represents a collection of items - Slice - // Enum represents an enumeration - Enum - // Map represents a map - Map - // Object is the generic object type - Object - // DOSPath represents the file system path in DOS device notation - DOSPath - // Path represents the file system path with normalized drive letter notation - Path - // Status represents the system error code message - Status - // Key represents the registry key - Key - // Flags represents a bitmask of flags - Flags - // Flags64 represents an extended (64 bits) bitmask of flags - Flags64 - // Address is the memory address reference - Address - // HandleType represents the handle type such as Mutex or File - HandleType + Null Type = 0 + Int8 Type = 3 + Uint8 Type = 4 + Int16 Type = 5 + Uint16 Type = 6 + Int32 Type = 7 + Uint32 Type = 8 + Int64 Type = 9 + Uint64 Type = 10 + Float Type = 11 + Double Type = 12 + Bool Type = 13 + Binary Type = 14 + PID Type = 18 + TID Type = 19 + Port Type = 21 + IP Type = 22 + IPv4 Type = 23 + IPv6 Type = 24 + Time Type = 25 + Slice Type = 26 + Enum Type = 27 + Map Type = 28 + Object Type = 29 + Path Type = 31 + Status Type = 32 + Flags Type = 34 + Flags64 Type = 35 + Address Type = 36 ) -// String return the type string representation. +// String returns the type name. func (t Type) String() string { + if name := platformTypeString(t); name != "" { + return name + } switch t { - case UnicodeString: - return "unicode" - case AnsiString: - return "ansi" case Int8: return "int8" case Uint8: @@ -124,8 +75,6 @@ func (t Type) String() string { return "int64" case Uint64: return "uint64" - case SID, WbemSID: - return "sid" case TID: return "tid" case PID: diff --git a/pkg/event/params/types_linux.go b/pkg/event/params/types_linux.go new file mode 100644 index 000000000..a7c933239 --- /dev/null +++ b/pkg/event/params/types_linux.go @@ -0,0 +1,33 @@ +//go:build linux + +/* + * Copyright 2026 by Mostafa Moradian + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package params + +const ( + // String is a UTF-8 encoded Linux string. + String Type = 1 +) + +func platformTypeString(t Type) string { + if t == String { + return "string" + } + return "" +} diff --git a/pkg/event/params/types_windows.go b/pkg/event/params/types_windows.go new file mode 100644 index 000000000..5a64fba36 --- /dev/null +++ b/pkg/event/params/types_windows.go @@ -0,0 +1,44 @@ +/* + * Copyright 2021-present by Nedim Sabic Sabic + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package params + +const ( + UnicodeString Type = 1 + AnsiString Type = 2 + GUID Type = 15 + Pointer Type = 16 + SID Type = 17 + WbemSID Type = 20 + DOSPath Type = 30 + Key Type = 33 + HandleType Type = 37 +) + +func platformTypeString(t Type) string { + switch t { + case UnicodeString: + return "unicode" + case AnsiString: + return "ansi" + case SID, WbemSID: + return "sid" + default: + return "" + } +} diff --git a/pkg/event/pid_linux.go b/pkg/event/pid_linux.go index 340f0367a..a16deb920 100644 --- a/pkg/event/pid_linux.go +++ b/pkg/event/pid_linux.go @@ -22,3 +22,6 @@ package event // PID is the process identifier type on Linux (kernel PIDs are 64-bit). type PID = uint64 + +// TID is the thread identifier type on Linux (kernel thread IDs are 64-bit). +type TID = uint64 diff --git a/pkg/event/pid_windows.go b/pkg/event/pid_windows.go index a93a7dc04..835c23063 100644 --- a/pkg/event/pid_windows.go +++ b/pkg/event/pid_windows.go @@ -22,3 +22,6 @@ package event // PID is the process identifier type on Windows. type PID = uint32 + +// TID is the thread identifier type on Windows. +type TID = uint32 diff --git a/pkg/event/queue.go b/pkg/event/queue.go index a580e253d..9055de150 100644 --- a/pkg/event/queue.go +++ b/pkg/event/queue.go @@ -43,9 +43,10 @@ type Listener interface { // Queue is the channel-backed data structure for // pushing captured events and invoking listeners. type Queue struct { + queuePlatform + q chan *Event listeners []Listener - decorator *StackwalkDecorator stackEnrichment bool enqueueAlways bool } @@ -58,7 +59,7 @@ func NewQueue(size int, stackEnrichment bool, enqueueAlways bool) *Queue { stackEnrichment: stackEnrichment, enqueueAlways: enqueueAlways, } - q.decorator = NewStackwalkDecorator(q) + q.initPlatform() return q } @@ -70,7 +71,7 @@ func NewQueueWithChannel(ch chan *Event, stackEnrichment bool, enqueueAlways boo stackEnrichment: stackEnrichment, enqueueAlways: enqueueAlways, } - q.decorator = NewStackwalkDecorator(q) + q.initPlatform() return q } @@ -84,7 +85,7 @@ func (q *Queue) RegisterListener(listener Listener) { func (q *Queue) Events() <-chan *Event { return q.q } // Close closes the queue disposing allocated resources. -func (q *Queue) Close() { q.decorator.Stop() } +func (q *Queue) Close() { q.closePlatform() } // Push pushes a new event to the channel. Prior to // sending the event to the channel, all registered @@ -107,20 +108,8 @@ func (q *Queue) Close() { q.decorator.Stop() } // enriched with callstack parameter and forwarded to the // event queue. func (q *Queue) Push(e *Event) error { - if q.stackEnrichment { - // store pending event for callstack enrichment - if e.Type.CanEnrichStack() { - q.decorator.Push(e) - return nil - } - // decorate events with callstack return addresses - if e.IsStackWalk() { - e = q.decorator.Pop(e) - } - } - // drop stack walk events - if e.IsStackWalk() { - return nil + if handled, err := q.pushPlatform(e); handled || err != nil { + return err } return q.push(e) } diff --git a/pkg/event/queue_linux.go b/pkg/event/queue_linux.go new file mode 100644 index 000000000..76705f077 --- /dev/null +++ b/pkg/event/queue_linux.go @@ -0,0 +1,29 @@ +//go:build linux + +/* + * Copyright 2026 by Mostafa Moradian + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package event + +type queuePlatform struct{} + +func (q *Queue) initPlatform() {} + +func (q *Queue) closePlatform() {} + +func (q *Queue) pushPlatform(_ *Event) (bool, error) { return false, nil } diff --git a/pkg/event/flags_linux.go b/pkg/event/queue_linux_test.go similarity index 68% rename from pkg/event/flags_linux.go rename to pkg/event/queue_linux_test.go index f7d187755..d6fdbcb35 100644 --- a/pkg/event/flags_linux.go +++ b/pkg/event/queue_linux_test.go @@ -20,21 +20,17 @@ package event -import "strings" +import ( + "testing" -type ParamFlag struct { - Name string - Value uint64 -} + "github.com/stretchr/testify/require" +) -type ParamFlags []ParamFlag +func TestLinuxQueuePush(t *testing.T) { + queue := NewQueue(1, false, false) + t.Cleanup(queue.Close) -func (flags ParamFlags) String(value uint64) string { - var names []string - for _, flag := range flags { - if value&flag.Value == flag.Value { - names = append(names, flag.Name) - } - } - return strings.Join(names, "|") + event := &Event{Type: Execve, PID: 42, Tid: 43} + require.NoError(t, queue.Push(event)) + require.Same(t, event, <-queue.Events()) } diff --git a/pkg/event/queue_windows.go b/pkg/event/queue_windows.go new file mode 100644 index 000000000..9866c468f --- /dev/null +++ b/pkg/event/queue_windows.go @@ -0,0 +1,48 @@ +/* + * Copyright 2021-2022 by Nedim Sabic Sabic + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package event + +type queuePlatform struct { + decorator *StackwalkDecorator +} + +func (q *Queue) initPlatform() { + q.decorator = NewStackwalkDecorator(q) +} + +func (q *Queue) closePlatform() { + q.decorator.Stop() +} + +func (q *Queue) pushPlatform(e *Event) (bool, error) { + if q.stackEnrichment { + if e.Type.CanEnrichStack() { + q.decorator.Push(e) + return true, nil + } + if e.IsStackWalk() { + q.decorator.Pop(e) + return true, nil + } + } + if e.IsStackWalk() { + return true, nil + } + return false, nil +} diff --git a/pkg/event/queue_test.go b/pkg/event/queue_windows_test.go similarity index 99% rename from pkg/event/queue_test.go rename to pkg/event/queue_windows_test.go index 05ee7f262..cd3fed7a0 100644 --- a/pkg/event/queue_test.go +++ b/pkg/event/queue_windows_test.go @@ -1,5 +1,3 @@ -//go:build windows - /* * Copyright 2021-2022 by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/pkg/event/stackwalk.go b/pkg/event/stackwalk_windows.go similarity index 99% rename from pkg/event/stackwalk.go rename to pkg/event/stackwalk_windows.go index 21077ab01..752ae39ad 100644 --- a/pkg/event/stackwalk.go +++ b/pkg/event/stackwalk_windows.go @@ -1,5 +1,3 @@ -//go:build windows - /* * Copyright 2021-present by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/pkg/event/stackwalk_test.go b/pkg/event/stackwalk_windows_test.go similarity index 99% rename from pkg/event/stackwalk_test.go rename to pkg/event/stackwalk_windows_test.go index c624151a8..285070555 100644 --- a/pkg/event/stackwalk_test.go +++ b/pkg/event/stackwalk_windows_test.go @@ -1,5 +1,3 @@ -//go:build windows - /* * Copyright 2021-present by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/pkg/event/template.go b/pkg/event/template.go index 8bd81f81a..151d1f925 100644 --- a/pkg/event/template.go +++ b/pkg/event/template.go @@ -137,6 +137,7 @@ func (e *Event) RenderCustomTemplate(tmpl *template.Template) ([]byte, error) { func renderTemplate(evt *Event, tmpl *template.Template) ([]byte, error) { var writer bytes.Buffer + opts := serializationOptions() data := struct { Evt *Event SerializeHandles bool @@ -146,11 +147,11 @@ func renderTemplate(evt *Event, tmpl *template.Template) ([]byte, error) { SerializePE bool }{ evt, - SerializeHandles, - SerializeThreads, - SerializeModules, - SerializeEnvs, - SerializePE, + opts.handles, + opts.threads, + opts.modules, + opts.envs, + opts.pe, } err := tmpl.Execute(&writer, data) if err != nil { diff --git a/pkg/event/types_linux.go b/pkg/event/types_linux.go index 0513861e4..8bb9b7140 100644 --- a/pkg/event/types_linux.go +++ b/pkg/event/types_linux.go @@ -25,54 +25,66 @@ import ( "github.com/rabbitstack/fibratus/pkg/util/hashers" ) +// Source identifies a Linux event source. type Source uint8 const ( - SystemLogger Source = iota - SecurityTelemetryLogger + // RawSyscallTracepoint identifies events from the raw_syscalls tracepoint. + RawSyscallTracepoint Source = iota ) +// Type identifies a Linux event type. type Type uint16 const ( UnknownType Type = iota - CreateProcess Execve - TerminateProcess Exit - ProcessRundown Clone - - // Windows-only event types stubbed so shared consumers (rules compiler) - // compile on Linux. These are never emitted by the Linux event source. - RegOpenKey - OpenThread - OpenProcess - SetFileInformation - CreateFile - MapViewFile - UnmapViewFile - SetThreadContext - CreateSymbolicLinkObject - CreateThread ) +// String returns the event type name. func (t Type) String() string { - return TypeToEventInfo(t).Name + switch t { + case Execve: + return "execve" + case Exit: + return "exit" + case Clone: + return "clone" + default: + return "" + } } +// Category returns the event type category. func (t Type) Category() Category { - return TypeToEventInfo(t).Category + switch t { + case Execve, Exit, Clone: + return Process + default: + return Unknown + } } -func (t Type) Subcategory() Subcategory { - return None -} +// Subcategory returns the event type subcategory. +func (t Type) Subcategory() Subcategory { return None } +// Description returns a brief description of the event type. func (t Type) Description() string { - return TypeToEventInfo(t).Description + switch t { + case Execve: + return "Executes a program" + case Exit: + return "Exit all threads in a process" + case Clone: + return "Creates a child process or a thread" + default: + return "" + } } +// Hash calculates the hash of the event type name. func (t Type) Hash() uint32 { if t == UnknownType { return 0 @@ -80,18 +92,17 @@ func (t Type) Hash() uint32 { return hashers.FnvUint32([]byte(t.String())) } +// Exists reports whether the event type is known. func (t Type) Exists() bool { - return t != UnknownType && t.String() != "N/A" -} - -func (t Type) OnlyState() bool { - return t == ProcessRundown -} - -func (t Type) CanEnrichStack() bool { - return false + switch t { + case Execve, Exit, Clone: + return true + default: + return false + } } +// UnmarshalYAML converts an event name to its type. func (t *Type) UnmarshalYAML(unmarshal func(interface{}) error) error { var name string if err := unmarshal(&name); err != nil { @@ -101,13 +112,11 @@ func (t *Type) UnmarshalYAML(unmarshal func(interface{}) error) error { return nil } -func (t Type) ID() uint { - return uint(t) -} +// ID returns the stable numeric event identifier. +func (t Type) ID() uint { return uint(t) } -func (t Type) Source() Source { - return SystemLogger -} +// Source returns the event source. +func (t Type) Source() Source { return RawSyscallTracepoint } func (t Type) color() string { return colorizer.SpanBold(colorizer.White, t.String()) From edecdce868f273a1e712a59629fa5779c8c77657 Mon Sep 17 00:00:00 2001 From: Mostafa Moradian Date: Mon, 10 Aug 2026 23:36:40 +0200 Subject: [PATCH 25/28] refactor(rules): adapt filtering to platform event models Split field/accessor/function registries and compiler behavior by platform, remove Linux-only Windows stubs, and preserve Windows-specific tests behind file suffixes. Use platform PID types and add Linux compiler coverage. --- pkg/config/filters.go | 6 +- pkg/filter/accessor_linux.go | 23 +- pkg/filter/accessor_narrow_windows.go | 105 ----- pkg/filter/accessor_windows.go | 83 ++++ pkg/filter/accessor_windows_test.go | 19 +- pkg/filter/fields/defs.go | 359 ++---------------- pkg/filter/fields/defs_linux.go | 36 ++ pkg/filter/fields/defs_linux_test.go | 42 ++ pkg/filter/fields/defs_windows.go | 322 ++++++++++++++++ ...{filter_test.go => filter_windows_test.go} | 5 +- pkg/filter/ql/function.go | 100 +---- ...n_callstack_linux.go => function_linux.go} | 30 ++ ...llstack_windows.go => function_windows.go} | 113 ++++++ ...ction_test.go => function_windows_test.go} | 0 .../{base_test.go => base_windows_test.go} | 0 .../{dir_test.go => dir_windows_test.go} | 0 .../{glob_test.go => glob_windows_test.go} | 0 ...{is_abs_test.go => is_abs_windows_test.go} | 0 ...{volume_test.go => volume_windows_test.go} | 0 ...iteral_test.go => literal_windows_test.go} | 0 ...{parser_test.go => parser_windows_test.go} | 0 pkg/filter/util.go | 9 - .../get_reg_value_linux.go => util_linux.go} | 11 +- ...cessor_narrow_linux.go => util_windows.go} | 26 +- pkg/rules/action/kill_linux.go | 8 +- pkg/rules/action/kill_windows.go | 8 +- pkg/rules/compiler.go | 35 +- .../compiler_linux.go} | 24 +- pkg/rules/compiler_linux_test.go | 52 +++ pkg/rules/compiler_windows.go | 63 +++ ...piler_test.go => compiler_windows_test.go} | 0 ...{engine_test.go => engine_windows_test.go} | 0 pkg/rules/sequence.go | 4 +- ...uence_test.go => sequence_windows_test.go} | 0 34 files changed, 857 insertions(+), 626 deletions(-) delete mode 100644 pkg/filter/accessor_narrow_windows.go create mode 100644 pkg/filter/fields/defs_linux.go create mode 100644 pkg/filter/fields/defs_linux_test.go create mode 100644 pkg/filter/fields/defs_windows.go rename pkg/filter/{filter_test.go => filter_windows_test.go} (99%) rename pkg/filter/ql/{function_callstack_linux.go => function_linux.go} (62%) rename pkg/filter/ql/{function_callstack_windows.go => function_windows.go} (51%) rename pkg/filter/ql/{function_test.go => function_windows_test.go} (100%) rename pkg/filter/ql/functions/{base_test.go => base_windows_test.go} (100%) rename pkg/filter/ql/functions/{dir_test.go => dir_windows_test.go} (100%) rename pkg/filter/ql/functions/{glob_test.go => glob_windows_test.go} (100%) rename pkg/filter/ql/functions/{is_abs_test.go => is_abs_windows_test.go} (100%) rename pkg/filter/ql/functions/{volume_test.go => volume_windows_test.go} (100%) rename pkg/filter/ql/{literal_test.go => literal_windows_test.go} (100%) rename pkg/filter/ql/{parser_test.go => parser_windows_test.go} (100%) rename pkg/filter/{ql/functions/get_reg_value_linux.go => util_linux.go} (72%) rename pkg/filter/{accessor_narrow_linux.go => util_windows.go} (60%) rename pkg/{filter/ql/functions/minidump_linux.go => rules/compiler_linux.go} (56%) create mode 100644 pkg/rules/compiler_linux_test.go create mode 100644 pkg/rules/compiler_windows.go rename pkg/rules/{compiler_test.go => compiler_windows_test.go} (100%) rename pkg/rules/{engine_test.go => engine_windows_test.go} (100%) rename pkg/rules/{sequence_test.go => sequence_windows_test.go} (100%) diff --git a/pkg/config/filters.go b/pkg/config/filters.go index e9eb3cffb..76e3fa92f 100644 --- a/pkg/config/filters.go +++ b/pkg/config/filters.go @@ -170,13 +170,13 @@ type ActionContext struct { // UniquePids returns a set of process identifiers // from each matched event to be used in actions // such as the process kill action. -func (ctx *ActionContext) UniquePids() []uint32 { - pids := make(map[uint32]struct{}) +func (ctx *ActionContext) UniquePids() []event.PID { + pids := make(map[event.PID]struct{}) for _, e := range ctx.Events { if e.IsCreateProcess() { pids[e.Params.MustGetPid()] = struct{}{} } else { - pids[uint32(e.PID)] = struct{}{} + pids[e.PID] = struct{}{} } } return convert.MapKeysToSlice(pids) diff --git a/pkg/filter/accessor_linux.go b/pkg/filter/accessor_linux.go index 069271f0d..432a11540 100644 --- a/pkg/filter/accessor_linux.go +++ b/pkg/filter/accessor_linux.go @@ -61,7 +61,7 @@ func (a *psAccessor) Get(f Field, e *event.Event) (params.Value, error) { return nil, ErrPsNil } return e.PS.Name, nil - case fields.PsComm, fields.PsCmdline: + case fields.PsCmdline: if e.PS == nil { return nil, ErrPsNil } @@ -115,3 +115,24 @@ func (a *psAccessor) Get(f Field, e *event.Event) (params.Value, error) { return nil, nil } } + +func (f *filter) pruneUnusedAccessors() { + removeEvtAccessor := true + removePsAccessor := true + + for _, field := range f.fields { + switch { + case field.Name.IsEvtField() || field.Name.IsKevtField(): + removeEvtAccessor = false + case field.Name.IsPsField(): + removePsAccessor = false + } + } + + if removeEvtAccessor { + f.removeAccessor(&evtAccessor{}) + } + if removePsAccessor { + f.removeAccessor(&psAccessor{}) + } +} diff --git a/pkg/filter/accessor_narrow_windows.go b/pkg/filter/accessor_narrow_windows.go deleted file mode 100644 index 239f17323..000000000 --- a/pkg/filter/accessor_narrow_windows.go +++ /dev/null @@ -1,105 +0,0 @@ -//go:build windows - -/* - * Copyright 2020-2021 by Nedim Sabic Sabic - * Copyright 2026 by Mostafa Moradian - * https://www.fibratus.io - * All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package filter - -func (f *filter) pruneUnusedAccessors() { - var ( - removeEvtAccessor = true - removePsAccessor = true - removeThreadAccessor = true - removeModuleAccessor = true - removeFileAccessor = true - removeRegistryAccessor = true - removeNetworkAccessor = true - removeHandleAccessor = true - removePEAccessor = true - removeMemAccessor = true - removeDNSAccessor = true - removeThreadpoolAccessor = true - ) - - for _, field := range f.fields { - switch { - case field.Name.IsEvtField() || field.Name.IsKevtField(): - removeEvtAccessor = false - case field.Name.IsPeField(): - removePEAccessor = false - case field.Name.IsPsField(): - removePsAccessor = false - case field.Name.IsThreadField(): - removeThreadAccessor = false - case field.Name.IsImageField() || field.Name.IsModuleField(): - removeModuleAccessor = false - case field.Name.IsFileField(): - removeFileAccessor = false - case field.Name.IsRegistryField(): - removeRegistryAccessor = false - case field.Name.IsNetworkField(): - removeNetworkAccessor = false - case field.Name.IsHandleField(): - removeHandleAccessor = false - case field.Name.IsMemField(): - removeMemAccessor = false - case field.Name.IsDNSField(): - removeDNSAccessor = false - case field.Name.IsThreadpoolField(): - removeThreadpoolAccessor = false - } - } - - if removeEvtAccessor { - f.removeAccessor(&evtAccessor{}) - } - if removePsAccessor { - f.removeAccessor(&psAccessor{}) - } - if removeThreadAccessor { - f.removeAccessor(&threadAccessor{}) - } - if removeModuleAccessor { - f.removeAccessor(&moduleAccessor{}) - } - if removeFileAccessor { - f.removeAccessor(&fileAccessor{}) - } - if removeRegistryAccessor { - f.removeAccessor(®istryAccessor{}) - } - if removeNetworkAccessor { - f.removeAccessor(&networkAccessor{}) - } - if removeHandleAccessor { - f.removeAccessor(&handleAccessor{}) - } - if removePEAccessor { - f.removeAccessor(&peAccessor{}) - } - if removeMemAccessor { - f.removeAccessor(&memAccessor{}) - } - if removeDNSAccessor { - f.removeAccessor(&dnsAccessor{}) - } - if removeThreadpoolAccessor { - f.removeAccessor(&threadpoolAccessor{}) - } -} diff --git a/pkg/filter/accessor_windows.go b/pkg/filter/accessor_windows.go index 25e60ee7e..2ca6dd527 100644 --- a/pkg/filter/accessor_windows.go +++ b/pkg/filter/accessor_windows.go @@ -1339,3 +1339,86 @@ func (*threadpoolAccessor) Get(f Field, e *event.Event) (params.Value, error) { return nil, nil } + +func (f *filter) pruneUnusedAccessors() { + var ( + removeEvtAccessor = true + removePsAccessor = true + removeThreadAccessor = true + removeModuleAccessor = true + removeFileAccessor = true + removeRegistryAccessor = true + removeNetworkAccessor = true + removeHandleAccessor = true + removePEAccessor = true + removeMemAccessor = true + removeDNSAccessor = true + removeThreadpoolAccessor = true + ) + + for _, field := range f.fields { + switch { + case field.Name.IsEvtField() || field.Name.IsKevtField(): + removeEvtAccessor = false + case field.Name.IsPeField(): + removePEAccessor = false + case field.Name.IsPsField(): + removePsAccessor = false + case field.Name.IsThreadField(): + removeThreadAccessor = false + case field.Name.IsImageField() || field.Name.IsModuleField(): + removeModuleAccessor = false + case field.Name.IsFileField(): + removeFileAccessor = false + case field.Name.IsRegistryField(): + removeRegistryAccessor = false + case field.Name.IsNetworkField(): + removeNetworkAccessor = false + case field.Name.IsHandleField(): + removeHandleAccessor = false + case field.Name.IsMemField(): + removeMemAccessor = false + case field.Name.IsDNSField(): + removeDNSAccessor = false + case field.Name.IsThreadpoolField(): + removeThreadpoolAccessor = false + } + } + + if removeEvtAccessor { + f.removeAccessor(&evtAccessor{}) + } + if removePsAccessor { + f.removeAccessor(&psAccessor{}) + } + if removeThreadAccessor { + f.removeAccessor(&threadAccessor{}) + } + if removeModuleAccessor { + f.removeAccessor(&moduleAccessor{}) + } + if removeFileAccessor { + f.removeAccessor(&fileAccessor{}) + } + if removeRegistryAccessor { + f.removeAccessor(®istryAccessor{}) + } + if removeNetworkAccessor { + f.removeAccessor(&networkAccessor{}) + } + if removeHandleAccessor { + f.removeAccessor(&handleAccessor{}) + } + if removePEAccessor { + f.removeAccessor(&peAccessor{}) + } + if removeMemAccessor { + f.removeAccessor(&memAccessor{}) + } + if removeDNSAccessor { + f.removeAccessor(&dnsAccessor{}) + } + if removeThreadpoolAccessor { + f.removeAccessor(&threadpoolAccessor{}) + } +} diff --git a/pkg/filter/accessor_windows_test.go b/pkg/filter/accessor_windows_test.go index c2164da48..10084a8d1 100644 --- a/pkg/filter/accessor_windows_test.go +++ b/pkg/filter/accessor_windows_test.go @@ -75,6 +75,17 @@ func TestNarrowAccessors(t *testing.T) { assert.Len(t, pea.fields, 3) } +func eventWithCallstack(typ event.Type, category event.Category) *event.Event { + e := &event.Event{Type: typ, Category: category} + e.Callstack = []callstack.Frame{{ + Addr: 0x7ffb5c1d0396, + Offset: 0x61, + Symbol: "CreateProcessW", + Module: "C:\\WINDOWS\\System32\\KERNELBASE.dll", + }} + return e +} + func TestIsFieldAccessible(t *testing.T) { var tests = []struct { a Accessor @@ -108,22 +119,22 @@ func TestIsFieldAccessible(t *testing.T) { }, { newThreadAccessor(), - &event.Event{Type: event.CreateProcess, Category: event.Process, Callstack: []callstack.Frame{{Addr: 0x7ffb5c1d0396, Offset: 0x61, Symbol: "CreateProcessW", Module: "C:\\WINDOWS\\System32\\KERNELBASE.dll"}}}, + eventWithCallstack(event.CreateProcess, event.Process), true, }, { newThreadAccessor(), - &event.Event{Type: event.RegSetValue, Category: event.Registry, Callstack: []callstack.Frame{{Addr: 0x7ffb5c1d0396, Offset: 0x61, Symbol: "CreateProcessW", Module: "C:\\WINDOWS\\System32\\KERNELBASE.dll"}}}, + eventWithCallstack(event.RegSetValue, event.Registry), true, }, { newRegistryAccessor(), - &event.Event{Type: event.RegSetValue, Category: event.Registry, Callstack: []callstack.Frame{{Addr: 0x7ffb5c1d0396, Offset: 0x61, Symbol: "CreateProcessW", Module: "C:\\WINDOWS\\System32\\KERNELBASE.dll"}}}, + eventWithCallstack(event.RegSetValue, event.Registry), true, }, { newNetworkAccessor(), - &event.Event{Type: event.RegSetValue, Category: event.Registry, Callstack: []callstack.Frame{{Addr: 0x7ffb5c1d0396, Offset: 0x61, Symbol: "CreateProcessW", Module: "C:\\WINDOWS\\System32\\KERNELBASE.dll"}}}, + eventWithCallstack(event.RegSetValue, event.Registry), false, }, { diff --git a/pkg/filter/fields/defs.go b/pkg/filter/fields/defs.go index 5743682ce..cafd29eb6 100644 --- a/pkg/filter/fields/defs.go +++ b/pkg/filter/fields/defs.go @@ -904,15 +904,13 @@ func IsPseudoField(f Field) bool { func (f Field) IsPeSectionsPseudo() bool { return f == PeSections || f == PsPeSections } -var fields = map[Field]FieldInfo{ +var commonFields = map[Field]FieldInfo{ EvtSeq: {EvtSeq, "event sequence number", params.Uint64, []string{"evt.seq > 666"}, nil, nil}, - EvtPID: {EvtPID, "process identifier generating the event", params.Uint32, []string{"evt.pid = 6"}, nil, nil}, - EvtTID: {EvtTID, "thread identifier generating the event", params.Uint32, []string{"evt.tid = 1024"}, nil, nil}, EvtCPU: {EvtCPU, "logical processor core where the event was generated", params.Uint8, []string{"evt.cpu = 2"}, nil, nil}, - EvtName: {EvtName, "symbolical event name", params.AnsiString, []string{"evt.name = 'CreateThread'"}, nil, nil}, - EvtCategory: {EvtCategory, "event category", params.AnsiString, []string{"evt.category = 'registry'"}, nil, nil}, - EvtDesc: {EvtDesc, "event description", params.AnsiString, []string{"evt.desc contains 'Creates a new process'"}, nil, nil}, - EvtHost: {EvtHost, "host name on which the event was produced", params.UnicodeString, []string{"evt.host contains 'kitty'"}, nil, nil}, + EvtName: {EvtName, "symbolical event name", platformAnsiString(), []string{"evt.name = 'CreateThread'"}, nil, nil}, + EvtCategory: {EvtCategory, "event category", platformAnsiString(), []string{"evt.category = 'registry'"}, nil, nil}, + EvtDesc: {EvtDesc, "event description", platformAnsiString(), []string{"evt.desc contains 'Creates a new process'"}, nil, nil}, + EvtHost: {EvtHost, "host name on which the event was produced", platformString(), []string{"evt.host contains 'kitty'"}, nil, nil}, EvtTime: {EvtTime, "event timestamp as a time string", params.Time, []string{"evt.time = '17:05:32'"}, nil, nil}, EvtTimeHour: {EvtTimeHour, "hour within the day on which the event occurred", params.Time, []string{"evt.time.h = 23"}, nil, nil}, EvtTimeMin: {EvtTimeMin, "minute offset within the hour on which the event occurred", params.Time, []string{"evt.time.m = 54"}, nil, nil}, @@ -922,9 +920,9 @@ var fields = map[Field]FieldInfo{ EvtDateDay: {EvtDateDay, "day of the month on which the event occurred", params.Time, []string{"evt.date.d = 12"}, nil, nil}, EvtDateMonth: {EvtDateMonth, "month of the year on which the event occurred", params.Time, []string{"evt.date.m = 11"}, nil, nil}, EvtDateYear: {EvtDateYear, "year on which the event occurred", params.Uint32, []string{"evt.date.y = 2020"}, nil, nil}, - EvtDateTz: {EvtDateTz, "time zone associated with the event timestamp", params.AnsiString, []string{"evt.date.tz = 'UTC'"}, nil, nil}, + EvtDateTz: {EvtDateTz, "time zone associated with the event timestamp", platformAnsiString(), []string{"evt.date.tz = 'UTC'"}, nil, nil}, EvtDateWeek: {EvtDateWeek, "week number within the year on which the event occurred", params.Uint8, []string{"evt.date.week = 2"}, nil, nil}, - EvtDateWeekday: {EvtDateWeekday, "week day on which the event occurred", params.AnsiString, []string{"evt.date.weekday = 'Monday'"}, nil, nil}, + EvtDateWeekday: {EvtDateWeekday, "week day on which the event occurred", platformAnsiString(), []string{"evt.date.weekday = 'Monday'"}, nil, nil}, EvtNparams: {EvtNparams, "number of parameters", params.Int8, []string{"evt.nparams > 2"}, nil, nil}, EvtArg: {EvtArg, "event parameter", params.Object, []string{"evt.arg[cmdline] istartswith 'C:\\Windows'"}, nil, &Argument{Optional: false, Pattern: "[a-z0-9_]+", ValidationFunc: func(s string) bool { for _, c := range s { @@ -938,17 +936,12 @@ var fields = map[Field]FieldInfo{ } return true }}}, - EvtIsDirectSyscall: {EvtIsDirectSyscall, "indicates if the event is performing a direct syscall", params.Bool, []string{"evt.is_direct_syscall = true"}, nil, nil}, - EvtIsIndirectSyscall: {EvtIsIndirectSyscall, "indicates if the event is performing an indirect syscall", params.Bool, []string{"evt.is_indirect_syscall = true"}, nil, nil}, - KevtSeq: {KevtSeq, "event sequence number", params.Uint64, []string{"kevt.seq > 666"}, &Deprecation{Since: "3.0.0", Fields: []Field{EvtSeq}}, nil}, - KevtPID: {KevtPID, "process identifier generating the event", params.Uint32, []string{"kevt.pid = 6"}, &Deprecation{Since: "3.0.0", Fields: []Field{EvtPID}}, nil}, - KevtTID: {KevtTID, "thread identifier generating the event", params.Uint32, []string{"kevt.tid = 1024"}, &Deprecation{Since: "3.0.0", Fields: []Field{EvtTID}}, nil}, KevtCPU: {KevtCPU, "logical processor core where the event was generated", params.Uint8, []string{"kevt.cpu = 2"}, &Deprecation{Since: "3.0.0", Fields: []Field{EvtCPU}}, nil}, - KevtName: {KevtName, "symbolical event name", params.AnsiString, []string{"kevt.name = 'CreateThread'"}, &Deprecation{Since: "3.0.0", Fields: []Field{EvtName}}, nil}, - KevtCategory: {KevtCategory, "event category", params.AnsiString, []string{"kevt.category = 'registry'"}, &Deprecation{Since: "3.0.0", Fields: []Field{EvtCategory}}, nil}, - KevtDesc: {KevtDesc, "event description", params.AnsiString, []string{"kevt.desc contains 'Creates a new process'"}, &Deprecation{Since: "3.0.0", Fields: []Field{EvtDesc}}, nil}, - KevtHost: {KevtHost, "host name on which the event was produced", params.UnicodeString, []string{"kevt.host contains 'kitty'"}, &Deprecation{Since: "3.0.0", Fields: []Field{EvtHost}}, nil}, + KevtName: {KevtName, "symbolical event name", platformAnsiString(), []string{"kevt.name = 'CreateThread'"}, &Deprecation{Since: "3.0.0", Fields: []Field{EvtName}}, nil}, + KevtCategory: {KevtCategory, "event category", platformAnsiString(), []string{"kevt.category = 'registry'"}, &Deprecation{Since: "3.0.0", Fields: []Field{EvtCategory}}, nil}, + KevtDesc: {KevtDesc, "event description", platformAnsiString(), []string{"kevt.desc contains 'Creates a new process'"}, &Deprecation{Since: "3.0.0", Fields: []Field{EvtDesc}}, nil}, + KevtHost: {KevtHost, "host name on which the event was produced", platformString(), []string{"kevt.host contains 'kitty'"}, &Deprecation{Since: "3.0.0", Fields: []Field{EvtHost}}, nil}, KevtTime: {KevtTime, "event timestamp as a time string", params.Time, []string{"kevt.time = '17:05:32'"}, &Deprecation{Since: "3.0.0", Fields: []Field{EvtTime}}, nil}, KevtTimeHour: {KevtTimeHour, "hour within the day on which the event occurred", params.Time, []string{"kevt.time.h = 23"}, &Deprecation{Since: "3.0.0", Fields: []Field{EvtTimeHour}}, nil}, KevtTimeMin: {KevtTimeMin, "minute offset within the hour on which the event occurred", params.Time, []string{"kevt.time.m = 54"}, &Deprecation{Since: "3.0.0", Fields: []Field{EvtTimeMin}}, nil}, @@ -958,9 +951,9 @@ var fields = map[Field]FieldInfo{ KevtDateDay: {KevtDateDay, "day of the month on which the event occurred", params.Time, []string{"kevt.date.d = 12"}, &Deprecation{Since: "3.0.0", Fields: []Field{EvtDateDay}}, nil}, KevtDateMonth: {KevtDateMonth, "month of the year on which the event occurred", params.Time, []string{"kevt.date.m = 11"}, &Deprecation{Since: "3.0.0", Fields: []Field{EvtDateMonth}}, nil}, KevtDateYear: {KevtDateYear, "year on which the event occurred", params.Uint32, []string{"kevt.date.y = 2020"}, &Deprecation{Since: "3.0.0", Fields: []Field{EvtDateYear}}, nil}, - KevtDateTz: {KevtDateTz, "time zone associated with the event timestamp", params.AnsiString, []string{"kevt.date.tz = 'UTC'"}, &Deprecation{Since: "3.0.0", Fields: []Field{EvtDateTz}}, nil}, + KevtDateTz: {KevtDateTz, "time zone associated with the event timestamp", platformAnsiString(), []string{"kevt.date.tz = 'UTC'"}, &Deprecation{Since: "3.0.0", Fields: []Field{EvtDateTz}}, nil}, KevtDateWeek: {KevtDateWeek, "week number within the year on which the event occurred", params.Uint8, []string{"kevt.date.week = 2"}, &Deprecation{Since: "3.0.0", Fields: []Field{EvtDateWeek}}, nil}, - KevtDateWeekday: {KevtDateWeekday, "week day on which the event occurred", params.AnsiString, []string{"kevt.date.weekday = 'Monday'"}, &Deprecation{Since: "3.0.0", Fields: []Field{EvtDateWeekday}}, nil}, + KevtDateWeekday: {KevtDateWeekday, "week day on which the event occurred", platformAnsiString(), []string{"kevt.date.weekday = 'Monday'"}, &Deprecation{Since: "3.0.0", Fields: []Field{EvtDateWeekday}}, nil}, KevtNparams: {KevtNparams, "number of parameters", params.Int8, []string{"kevt.nparams > 2"}, &Deprecation{Since: "3.0.0", Fields: []Field{EvtNparams}}, nil}, KevtArg: {KevtArg, "event parameter", params.Object, []string{"kevt.arg[cmdline] istartswith 'C:\\Windows'"}, &Deprecation{Since: "3.0.0", Fields: []Field{EvtArg}}, &Argument{Optional: false, Pattern: "[a-z0-9_]+", ValidationFunc: func(s string) bool { for _, c := range s { @@ -974,313 +967,27 @@ var fields = map[Field]FieldInfo{ } return true }}}, + PsName: {PsName, "process image name including the file extension", platformString(), []string{"ps.name contains 'firefox'"}, nil, nil}, + PsCmdline: {PsCmdline, "process command line", platformString(), []string{"ps.cmdline contains 'java'"}, nil, nil}, + PsExe: {PsExe, "full name of the process' executable", platformString(), []string{"ps.exe = 'C:\\Windows\\system32\\cmd.exe'"}, nil, nil}, + PsArgs: {PsArgs, "process command line arguments", params.Slice, []string{"ps.args in ('/cdir', '/-C')"}, nil, nil}, + PsCwd: {PsCwd, "process current working directory", platformString(), []string{"ps.cwd = 'C:\\Users\\Default'"}, nil, nil}, + PsUsername: {PsUsername, "process username", platformString(), []string{"ps.username contains 'system'"}, nil, nil}, + PsEnvs: {PsEnvs, "process environment variables", params.Slice, []string{"ps.envs in ('SystemRoot:C:\\WINDOWS')", "ps.envs[windir] = 'C:\\WINDOWS'"}, nil, &Argument{Optional: true, ValidationFunc: func(arg string) bool { return true }}}, + PsParentName: {PsParentName, "parent process image name including the file extension", platformString(), []string{"ps.parent.name contains 'cmd.exe'"}, nil, nil}, + PsParentCmdline: {PsParentCmdline, "parent process command line", platformString(), []string{"ps.parent.cmdline contains 'java'"}, nil, nil}, + PsParentExe: {PsParentExe, "full name of the parent process' executable", platformString(), []string{"ps.parent.exe = 'C:\\Windows\\system32\\explorer.exe'"}, nil, nil}, +} - PsPid: {PsPid, "process identifier", params.PID, []string{"ps.pid = 1024"}, nil, nil}, - PsPpid: {PsPpid, "parent process identifier", params.PID, []string{"ps.ppid = 45"}, nil, nil}, - PsName: {PsName, "process image name including the file extension", params.UnicodeString, []string{"ps.name contains 'firefox'"}, nil, nil}, - PsComm: {PsComm, "process command line", params.UnicodeString, []string{"ps.comm contains 'java'"}, &Deprecation{Since: "1.10.0", Fields: []Field{PsCmdline}}, nil}, - PsCmdline: {PsCmdline, "process command line", params.UnicodeString, []string{"ps.cmdline contains 'java'"}, nil, nil}, - PsExe: {PsExe, "full name of the process' executable", params.UnicodeString, []string{"ps.exe = 'C:\\Windows\\system32\\cmd.exe'"}, nil, nil}, - PsArgs: {PsArgs, "process command line arguments", params.Slice, []string{"ps.args in ('/cdir', '/-C')"}, nil, nil}, - PsCwd: {PsCwd, "process current working directory", params.UnicodeString, []string{"ps.cwd = 'C:\\Users\\Default'"}, nil, nil}, - PsSID: {PsSID, "security identifier under which this process is run", params.UnicodeString, []string{"ps.sid contains 'SYSTEM'"}, nil, nil}, - PsSessionID: {PsSessionID, "unique identifier for the current session", params.Int16, []string{"ps.sessionid = 1"}, nil, nil}, - PsDomain: {PsDomain, "process domain", params.UnicodeString, []string{"ps.domain contains 'SERVICE'"}, nil, nil}, - PsUsername: {PsUsername, "process username", params.UnicodeString, []string{"ps.username contains 'system'"}, nil, nil}, - PsEnvs: {PsEnvs, "process environment variables", params.Slice, []string{"ps.envs in ('SystemRoot:C:\\WINDOWS')", "ps.envs[windir] = 'C:\\WINDOWS'"}, nil, &Argument{Optional: true, ValidationFunc: func(arg string) bool { return true }}}, - PsHandleNames: {PsHandleNames, "allocated process handle names", params.Slice, []string{"ps.handles in ('\\BaseNamedObjects\\__ComCatalogCache__')"}, nil, nil}, - PsHandleTypes: {PsHandleTypes, "allocated process handle types", params.Slice, []string{"ps.handle.types in ('Key', 'Mutant', 'Section')"}, nil, nil}, - PsDTB: {PsDTB, "process directory table base address", params.Address, []string{"ps.dtb = '7ffe0000'"}, nil, nil}, - PsModuleNames: {PsModuleNames, "modules loaded by the process", params.Slice, []string{"ps.modules in ('crypt32.dll', 'xul.dll')"}, nil, nil}, - PsParentName: {PsParentName, "parent process image name including the file extension", params.UnicodeString, []string{"ps.parent.name contains 'cmd.exe'"}, nil, nil}, - PsParentPid: {PsParentPid, "parent process id", params.Uint32, []string{"ps.parent.pid = 4"}, nil, nil}, - PsParentComm: {PsParentComm, "parent process command line", params.UnicodeString, []string{"ps.parent.comm contains 'java'"}, &Deprecation{Since: "1.10.0", Fields: []Field{PsParentCmdline}}, nil}, - PsParentCmdline: {PsParentCmdline, "parent process command line", params.UnicodeString, []string{"ps.parent.cmdline contains 'java'"}, nil, nil}, - PsParentExe: {PsParentExe, "full name of the parent process' executable", params.UnicodeString, []string{"ps.parent.exe = 'C:\\Windows\\system32\\explorer.exe'"}, nil, nil}, - PsParentArgs: {PsParentArgs, "parent process command line arguments", params.Slice, []string{"ps.parent.args in ('/cdir', '/-C')"}, nil, nil}, - PsParentCwd: {PsParentCwd, "parent process current working directory", params.UnicodeString, []string{"ps.parent.cwd = 'C:\\Temp'"}, nil, nil}, - PsParentSID: {PsParentSID, "security identifier under which the parent process is run", params.UnicodeString, []string{"ps.parent.sid contains 'SYSTEM'"}, nil, nil}, - PsParentDomain: {PsParentDomain, "parent process domain", params.UnicodeString, []string{"ps.parent.domain contains 'SERVICE'"}, nil, nil}, - PsParentUsername: {PsParentUsername, "parent process username", params.UnicodeString, []string{"ps.parent.username contains 'system'"}, nil, nil}, - PsParentSessionID: {PsParentSessionID, "unique identifier for the current session of parent process", params.Int16, []string{"ps.parent.sessionid = 1"}, nil, nil}, - PsParentEnvs: {PsParentEnvs, "parent process environment variables", params.Slice, []string{"ps.parent.envs in ('MOZ_CRASHREPORTER_DATA_DIRECTORY')"}, nil, nil}, - PsParentHandles: {PsParentHandles, "allocated parent process handle names", params.Slice, []string{"ps.parent.handles in ('\\BaseNamedObjects\\__ComCatalogCache__')"}, nil, nil}, - PsParentHandleTypes: {PsParentHandleTypes, "allocated parent process handle types", params.Slice, []string{"ps.parent.handle.types in ('File', 'SymbolicLink')"}, nil, nil}, - PsParentDTB: {PsParentDTB, "parent process directory table base address", params.Address, []string{"ps.parent.dtb = '7ffe0000'"}, nil, nil}, - PsAccessMask: {PsAccessMask, "process desired access rights", params.AnsiString, []string{"ps.access.mask = '0x1400'"}, nil, nil}, - PsAccessMaskNames: {PsAccessMaskNames, "process desired access rights as a string list", params.Slice, []string{"ps.access.mask.names in ('SUSPEND_RESUME')"}, nil, nil}, - PsAccessStatus: {PsAccessStatus, "process access status", params.UnicodeString, []string{"ps.access.status = 'access is denied.'"}, nil, nil}, - PsUUID: {PsUUID, "unique process identifier", params.Uint64, []string{"ps.uuid > 6000054355"}, nil, nil}, - PsParentUUID: {PsParentUUID, "unique parent process identifier", params.Uint64, []string{"ps.parent.uuid > 6000054355"}, nil, nil}, - PsIsWOW64Field: {PsIsWOW64Field, "indicates if the process generating the event is a 32-bit process created in 64-bit Windows system", params.Bool, []string{"ps.is_wow64"}, nil, nil}, - PsIsPackagedField: {PsIsPackagedField, "indicates if the process generating the event is packaged with the MSIX technology", params.Bool, []string{"ps.is_packaged"}, nil, nil}, - PsIsProtectedField: {PsIsProtectedField, "indicates if the process generating the event is a protected process", params.Bool, []string{"ps.is_protected"}, nil, nil}, - PsParentIsWOW64Field: {PsParentIsWOW64Field, "indicates if the parent process generating the event is a 32-bit process created in 64-bit Windows system", params.Bool, []string{"ps.parent.is_wow64"}, nil, nil}, - PsParentIsPackagedField: {PsParentIsPackagedField, "indicates if the parent process generating the event is packaged with the MSIX technology", params.Bool, []string{"ps.parent.is_packaged"}, nil, nil}, - PsParentIsProtectedField: {PsParentIsProtectedField, "indicates if the the parent process generating the event is a protected process", params.Bool, []string{"ps.parent.is_protected"}, nil, nil}, - PsAncestor: {PsAncestor, "the process ancestor name", params.UnicodeString, []string{"ps.ancestor[1] = 'svchost.exe'", "ps.ancestor in ('winword.exe')"}, nil, &Argument{Optional: true, Pattern: "[0-9]+", ValidationFunc: isNumber}}, - PsTokenIntegrityLevel: {PsTokenIntegrityLevel, "process token integrity level", params.UnicodeString, []string{"ps.token.integrity_level = 'SYSTEM'"}, nil, nil}, - PsTokenIsElevated: {PsTokenIsElevated, "indicates if the process token is elevated", params.Bool, []string{"ps.token.is_elevated = true"}, nil, nil}, - PsTokenElevationType: {PsTokenElevationType, "process token elevation type", params.AnsiString, []string{"ps.token.elevation_type = 'LIMITED'"}, nil, nil}, - PsParentTokenIntegrityLevel: {PsParentTokenIntegrityLevel, "parent process token integrity level", params.UnicodeString, []string{"ps.parent.token.integrity_level = 'HIGH'"}, nil, nil}, - PsParentTokenIsElevated: {PsParentTokenIsElevated, "indicates if the parent process token is elevated", params.Bool, []string{"ps.parent.token.is_elevated = true"}, nil, nil}, - PsParentTokenElevationType: {PsParentTokenElevationType, "parent process token elevation type", params.AnsiString, []string{"ps.parent.token.elevation_type = 'LIMITED'"}, nil, nil}, - PsSignatureExists: {PsSignatureExists, "indicates if the process executable has a valid signature", params.Bool, []string{"ps.signature.exists"}, nil, nil}, - PsSignatureTrusted: {PsSignatureTrusted, "indicates if the process executable signature certificate chain is trusted", params.Bool, []string{"ps.signature.trusted"}, nil, nil}, - PsSignatureSerial: {PsSignatureSerial, "represents signature serial number", params.UnicodeString, []string{"ps.signature.serial = '330000023241fb59996dcc4dff000000000232'"}, nil, nil}, - PsSignatureSubject: {PsSignatureSubject, "represents signature subject", params.UnicodeString, []string{"ps.signature.subject contains 'Washington, Redmond, Microsoft Corporation'"}, nil, nil}, - PsSignatureIssuer: {PsSignatureIssuer, "represents signature CA", params.UnicodeString, []string{"ps.signature.issuer contains 'Washington, Redmond, Microsoft Corporation'"}, nil, nil}, - PsSignatureAfter: {PsSignatureAfter, "represents certificate expiration date", params.Time, []string{"ps.signature.after contains '2024-02-01 00:05:42 +0000 UTC'"}, nil, nil}, - PsSignatureBefore: {PsSignatureBefore, "represents certificate enrollment date", params.Time, []string{"ps.signature.before contains '2024-02-01 00:05:42 +0000 UTC'"}, nil, nil}, - - PsPeNumSections: {PsPeNumSections, "number of PE sections", params.Uint16, []string{"ps.pe.nsections < 5"}, nil, nil}, - PsPeNumSymbols: {PsPeNumSymbols, "number of entries in the symbol table", params.Uint32, []string{"ps.pe.nsymbols > 230"}, nil, nil}, - PsPeBaseAddress: {PsPeBaseAddress, "executable base address", params.Address, []string{"ps.pe.address.base = '140000000'"}, nil, nil}, - PsPeEntrypoint: {PsPeEntrypoint, "address of the entrypoint function", params.Address, []string{"ps.pe.address.entrypoint = '20110'"}, nil, nil}, - PsPeSymbols: {PsPeSymbols, "imported symbols", params.Slice, []string{"ps.pe.symbols in ('GetTextFaceW', 'GetProcessHeap')"}, nil, nil}, - PsPeImports: {PsPeImports, "imported dynamic linked libraries", params.Slice, []string{"ps.pe.imports in ('msvcrt.dll', 'GDI32.dll'"}, nil, nil}, - PsPeResources: {PsPeResources, "version resources", params.Map, []string{"ps.pe.resources[FileDescription] = 'Notepad'"}, nil, &Argument{Optional: true, Pattern: "[a-zA-Z0-9_]+", ValidationFunc: func(s string) bool { - for _, c := range s { - switch { - case unicode.IsLower(c): - case unicode.IsUpper(c): - case unicode.IsNumber(c): - case c == '_': - default: - return false - } - } - return true - }}}, - PsPeCompany: {PsPeCompany, "internal company name of the file provided at compile-time", params.UnicodeString, []string{"ps.pe.company = 'Microsoft Corporation'"}, nil, nil}, - PsPeCopyright: {PsPeCopyright, "copyright notice for the file emitted at compile-time", params.UnicodeString, []string{"ps.pe.copyright = '© Microsoft Corporation'"}, nil, nil}, - PsPeDescription: {PsPeDescription, "internal description of the file provided at compile-time", params.UnicodeString, []string{"ps.pe.description = 'Notepad'"}, nil, nil}, - PsPeFileName: {PsPeFileName, "original file name supplied at compile-time", params.UnicodeString, []string{"ps.pe.file.name = 'NOTEPAD.EXE'"}, nil, nil}, - PsPeFileVersion: {PsPeFileVersion, "file version supplied at compile-time", params.UnicodeString, []string{"ps.pe.file.version = '10.0.18362.693 (WinBuild.160101.0800)'"}, nil, nil}, - PsPeProduct: {PsPeProduct, "internal product name of the file provided at compile-time", params.UnicodeString, []string{"ps.pe.product = 'Microsoft® Windows® Operating System'"}, nil, nil}, - PsPeProductVersion: {PsPeProductVersion, "internal product version of the file provided at compile-time", params.UnicodeString, []string{"ps.pe.product.version = '10.0.18362.693'"}, nil, nil}, - PsPeImphash: {PsPeImphash, "import hash", params.AnsiString, []string{"pe.impash = '5d3861c5c547f8a34e471ba273a732b2'"}, nil, nil}, - PsPeIsDotnet: {PsPeIsDotnet, "indicates if PE contains CLR data", params.Bool, []string{"ps.pe.is_dotnet"}, nil, nil}, - PsPeAnomalies: {PsPeAnomalies, "contains PE anomalies detected during parsing", params.Slice, []string{"ps.pe.anomalies in ('number of sections is 0')"}, nil, nil}, - PsPeIsModified: {PsPeIsModified, "indicates if disk and in-memory PE headers differ", params.Bool, []string{"ps.pe.is_modified"}, nil, nil}, - - ThreadBasePrio: {ThreadBasePrio, "scheduler priority of the thread", params.Int8, []string{"thread.prio = 5"}, nil, nil}, - ThreadIOPrio: {ThreadIOPrio, "I/O priority hint for scheduling I/O operations", params.Int8, []string{"thread.io.prio = 4"}, nil, nil}, - ThreadPagePrio: {ThreadPagePrio, "memory page priority hint for memory pages accessed by the thread", params.Int8, []string{"thread.page.prio = 12"}, nil, nil}, - ThreadKstackBase: {ThreadKstackBase, "base address of the thread's kernel space stack", params.Address, []string{"thread.kstack.base = 'a65d800000'"}, nil, nil}, - ThreadKstackLimit: {ThreadKstackLimit, "limit of the thread's kernel space stack", params.Address, []string{"thread.kstack.limit = 'a85d800000'"}, nil, nil}, - ThreadUstackBase: {ThreadUstackBase, "base address of the thread's user space stack", params.Address, []string{"thread.ustack.base = '7ffe0000'"}, nil, nil}, - ThreadUstackLimit: {ThreadUstackLimit, "limit of the thread's user space stack", params.Address, []string{"thread.ustack.limit = '8ffe0000'"}, nil, nil}, - ThreadEntrypoint: {ThreadEntrypoint, "starting address of the function to be executed by the thread", params.Address, []string{"thread.entrypoint = '7efe0000'"}, &Deprecation{Since: "2.3.0", Fields: []Field{ThreadStartAddress}}, nil}, - ThreadStartAddress: {ThreadStartAddress, "thread start address", params.Address, []string{"thread.start_address = '7efe0000'"}, nil, nil}, - ThreadStartAddressSymbol: {ThreadStartAddressSymbol, "thread start address symbol", params.UnicodeString, []string{"thread.start_address.symbol = 'LoadModule'"}, nil, nil}, - ThreadStartAddressModule: {ThreadStartAddressModule, "thread start address module", params.UnicodeString, []string{"thread.start_address.module endswith 'kernel32.dll'"}, nil, nil}, - ThreadPID: {ThreadPID, "the process identifier where the thread is created", params.Uint32, []string{"evt.pid != thread.pid"}, nil, nil}, - ThreadTEB: {ThreadTEB, "the base address of the thread environment block", params.Address, []string{"thread.teb_address = '8f30893000'"}, nil, nil}, - ThreadAccessMask: {ThreadAccessMask, "thread desired access rights", params.AnsiString, []string{"thread.access.mask = '0x1fffff'"}, nil, nil}, - ThreadAccessMaskNames: {ThreadAccessMaskNames, "thread desired access rights as a string list", params.Slice, []string{"thread.access.mask.names in ('IMPERSONATE')"}, nil, nil}, - ThreadAccessStatus: {ThreadAccessStatus, "thread access status", params.UnicodeString, []string{"thread.access.status = 'success'"}, nil, nil}, - ThreadCallstackSummary: {ThreadCallstackSummary, "callstack summary", params.UnicodeString, []string{"thread.callstack.summary contains 'ntdll.dll|KERNELBASE.dll'"}, nil, nil}, - ThreadCallstackKernelSummary: {ThreadCallstackKernelSummary, "kernel thread callstack summary", params.UnicodeString, []string{"thread.callstack.kernel_summary contains 'fileinfo.sys|ntoskrnl.exe|FLTMGR.SYS|ntoskrnl.exe'"}, nil, nil}, - ThreadCallstackDetail: {ThreadCallstackDetail, "detailed information of each stack frame", params.UnicodeString, []string{"thread.callstack.detail contains 'KERNELBASE.dll!CreateProcessW'"}, nil, nil}, - ThreadCallstackModules: {ThreadCallstackModules, "list of modules comprising the callstack", params.Slice, []string{"thread.callstack.modules in ('C:\\WINDOWS\\System32\\KERNELBASE.dll')", "base(thread.callstack.modules[7]) = 'ntdll.dll'"}, nil, &Argument{Optional: true, Pattern: "[0-9]+", ValidationFunc: isNumber}}, - ThreadCallstackSymbols: {ThreadCallstackSymbols, "list of symbols comprising the callstack", params.Slice, []string{"thread.callstack.symbols in ('ntdll.dll!NtCreateProcess')", "thread.callstack.symbols[3] = 'ntdll!NtCreateProcess'"}, nil, &Argument{Optional: true, Pattern: "[0-9]+", ValidationFunc: isNumber}}, - ThreadCallstackAllocationSizes: {ThreadCallstackAllocationSizes, "allocation sizes of private pages", params.Slice, []string{"thread.callstack.allocation_sizes > 10000"}, nil, nil}, - ThreadCallstackProtections: {ThreadCallstackProtections, "page protections masks of each frame", params.Slice, []string{"thread.callstack.protections in ('RWX', 'WX')"}, nil, nil}, - ThreadCallstackCallsiteLeadingAssembly: {ThreadCallstackCallsiteLeadingAssembly, "callsite leading assembly instructions", params.Slice, []string{"thread.callstack.callsite_leading_assembly in ('mov r10,rcx', 'syscall')"}, nil, nil}, - ThreadCallstackCallsiteTrailingAssembly: {ThreadCallstackCallsiteTrailingAssembly, "callsite trailing assembly instructions", params.Slice, []string{"thread.callstack.callsite_trailing_assembly in ('add esp, 0xab')"}, nil, nil}, - ThreadCallstackIsUnbacked: {ThreadCallstackIsUnbacked, "indicates if the callstack contains unbacked regions", params.Bool, []string{"thread.callstack.is_unbacked"}, nil, nil}, - ThreadCallstackAddresses: {ThreadCallstackAddresses, "list of all stack return addresses", params.Slice, []string{"thread.callstack.addresses in ('7ffb5c1d0396')"}, nil, nil}, - ThreadCallstackFinalUserModuleName: {ThreadCallstackFinalUserModuleName, "final user space stack frame module name", params.UnicodeString, []string{"thread.callstack.final_user_module.name != 'ntdll.dll'"}, nil, nil}, - ThreadCallstackFinalUserModulePath: {ThreadCallstackFinalUserModulePath, "final user space stack frame module path", params.UnicodeString, []string{"thread.callstack.final_user_module.path imatches '?:\\Windows\\System32\\ntdll.dll'"}, nil, nil}, - ThreadCallstackFinalUserSymbolName: {ThreadCallstackFinalUserSymbolName, "final user space stack symbol name", params.UnicodeString, []string{"thread.callstack.final_user_symbol.name imatches 'CreateProcess*'"}, nil, nil}, - ThreadCallstackFinalKernelModuleName: {ThreadCallstackFinalKernelModuleName, "final kernel space stack frame module name", params.UnicodeString, []string{"thread.callstack.final_kernel_module.name = 'FLTMGR.SYS'"}, nil, nil}, - ThreadCallstackFinalKernelModulePath: {ThreadCallstackFinalKernelModulePath, "final kernel space stack frame module path", params.UnicodeString, []string{"thread.callstack.final_kernel_module.path imatches '?:\\WINDOWS\\System32\\drivers\\FLTMGR.SYS'"}, nil, nil}, - ThreadCallstackFinalKernelSymbolName: {ThreadCallstackFinalKernelSymbolName, "final kernel space stack symbol name", params.UnicodeString, []string{"thread.callstack.final_kernel_symbol.name = 'FltGetStreamContext'"}, nil, nil}, - ThreadCallstackFinalUserModuleSignatureExists: {ThreadCallstackFinalUserModuleSignatureExists, "signature status of the final user space stack frame module", params.Bool, []string{"thread.callstack.final_user_module.signature.exists = true"}, nil, nil}, - ThreadCallstackFinalUserModuleSignatureTrusted: {ThreadCallstackFinalUserModuleSignatureTrusted, "signature trust status of the final user space stack frame module", params.Bool, []string{"thread.callstack.final_user_module.signature.trusted = true"}, nil, nil}, - ThreadCallstackFinalUserModuleSignatureIssuer: {ThreadCallstackFinalUserModuleSignatureIssuer, "final user space stack frame module signature certificate issuer", params.UnicodeString, []string{"thread.callstack.final_user_module.signature.issuer imatches '*Microsoft Corporation*'"}, nil, nil}, - ThreadCallstackFinalUserModuleSignatureSubject: {ThreadCallstackFinalUserModuleSignatureSubject, "final user space stack frame module signature certificate subject", params.UnicodeString, []string{"thread.callstack.final_user_module.signature.subject imatches '*Microsoft Windows*'"}, nil, nil}, - - ImagePath: {ImagePath, "full image path", params.UnicodeString, []string{"image.path = 'C:\\Windows\\System32\\advapi32.dll'"}, &Deprecation{Since: "3.0.0", Fields: []Field{ModulePath}}, nil}, - ImageName: {ImageName, "image name", params.UnicodeString, []string{"image.name = 'advapi32.dll'"}, &Deprecation{Since: "3.0.0", Fields: []Field{ModuleName}}, nil}, - ImageBase: {ImageBase, "the base address of process in which the image is loaded", params.Address, []string{"image.base.address = 'a65d800000'"}, &Deprecation{Since: "3.0.0", Fields: []Field{ModuleBase}}, nil}, - ImageChecksum: {ImageChecksum, "image checksum", params.Uint32, []string{"image.checksum = 746424"}, &Deprecation{Since: "3.0.0", Fields: []Field{ModuleChecksum}}, nil}, - ImageSize: {ImageSize, "image size", params.Uint32, []string{"image.size > 1024"}, &Deprecation{Since: "3.0.0", Fields: []Field{ModuleSize}}, nil}, - ImageDefaultAddress: {ImageDefaultAddress, "default image address", params.Address, []string{"image.default.address = '7efe0000'"}, &Deprecation{Since: "3.0.0", Fields: []Field{ModuleDefaultAddress}}, nil}, - ImagePID: {ImagePID, "target process identifier", params.Uint32, []string{"image.pid = 80"}, &Deprecation{Since: "3.0.0", Fields: []Field{ModulePID}}, nil}, - ImageSignatureType: {ImageSignatureType, "image signature type", params.AnsiString, []string{"image.signature.type != 'NONE'"}, &Deprecation{Since: "3.0.0", Fields: []Field{ModuleSignatureType}}, nil}, - ImageSignatureLevel: {ImageSignatureLevel, "image signature level", params.AnsiString, []string{"image.signature.level = 'AUTHENTICODE'"}, &Deprecation{Since: "3.0.0", Fields: []Field{ModuleSignatureLevel}}, nil}, - ImageCertSerial: {ImageCertSerial, "image certificate serial number", params.UnicodeString, []string{"image.cert.serial = '330000023241fb59996dcc4dff000000000232'"}, &Deprecation{Since: "3.0.0", Fields: []Field{ModuleSignatureSerial}}, nil}, - ImageCertSubject: {ImageCertSubject, "image certificate subject", params.UnicodeString, []string{"image.cert.subject contains 'Washington, Redmond, Microsoft Corporation'"}, &Deprecation{Since: "3.0.0", Fields: []Field{ModuleSignatureSubject}}, nil}, - ImageCertIssuer: {ImageCertIssuer, "image certificate CA", params.UnicodeString, []string{"image.cert.issuer contains 'Washington, Redmond, Microsoft Corporation'"}, &Deprecation{Since: "3.0.0", Fields: []Field{ModuleSignatureIssuer}}, nil}, - ImageCertAfter: {ImageCertAfter, "image certificate expiration date", params.Time, []string{"image.cert.after contains '2024-02-01 00:05:42 +0000 UTC'"}, &Deprecation{Since: "3.0.0", Fields: []Field{ModuleSignatureAfter}}, nil}, - ImageCertBefore: {ImageCertBefore, "image certificate enrollment date", params.Time, []string{"image.cert.before contains '2024-02-01 00:05:42 +0000 UTC'"}, &Deprecation{Since: "3.0.0", Fields: []Field{ModuleSignatureBefore}}, nil}, - ImageIsDLL: {ImageIsDLL, "indicates if the loaded image is a DLL", params.Bool, []string{"image.is_dll'"}, &Deprecation{Since: "3.0.0", Fields: []Field{ModuleIsDLL}}, nil}, - ImageIsDriver: {ImageIsDriver, "indicates if the loaded image is a driver", params.Bool, []string{"image.is_driver'"}, &Deprecation{Since: "3.0.0", Fields: []Field{ModuleIsDriver}}, nil}, - ImageIsExecutable: {ImageIsExecutable, "indicates if the loaded image is an executable", params.Bool, []string{"image.is_exec'"}, &Deprecation{Since: "3.0.0", Fields: []Field{ModuleIsExecutable}}, nil}, - ImageIsDotnet: {ImageIsDotnet, "indicates if the loaded image is a .NET assembly", params.Bool, []string{"image.is_dotnet'"}, &Deprecation{Since: "3.0.0", Fields: []Field{ModuleIsDotnet}}, nil}, - ModulePath: {ModulePath, "full module path", params.UnicodeString, []string{"module.path = 'C:\\Windows\\System32\\advapi32.dll'"}, nil, nil}, - ModulePathStem: {ModulePathStem, "module path stem", params.UnicodeString, []string{"module.path.stem = 'C:\\Windows\\System32\\advapi32'"}, nil, nil}, - ModuleName: {ModuleName, "module name", params.UnicodeString, []string{"module.name = 'advapi32.dll'"}, nil, nil}, - ModuleBase: {ModuleBase, "the base address of process in which the module is loaded", params.Address, []string{"module.base.address = 'a65d800000'"}, nil, nil}, - ModuleChecksum: {ModuleChecksum, "module checksum", params.Uint32, []string{"module.checksum = 746424"}, nil, nil}, - ModuleSize: {ModuleSize, "module size", params.Uint32, []string{"module.size > 1024"}, nil, nil}, - ModuleDefaultAddress: {ModuleDefaultAddress, "default module address", params.Address, []string{"module.default_address = '7efe0000'"}, nil, nil}, - ModulePID: {ModulePID, "target process identifier", params.Uint32, []string{"module.pid = 80"}, nil, nil}, - ModuleSignatureType: {ModuleSignatureType, "module signature type", params.AnsiString, []string{"module.signature.type != 'NONE'"}, nil, nil}, - ModuleSignatureLevel: {ModuleSignatureLevel, "module signature level", params.AnsiString, []string{"module.signature.level = 'AUTHENTICODE'"}, nil, nil}, - ModuleSignatureExists: {ModuleSignatureExists, "indicates if the module is signed", params.Bool, []string{"module.signature.exists = true"}, nil, nil}, - ModuleSignatureTrusted: {ModuleSignatureTrusted, "indicates if the module signature is trusted", params.Bool, []string{"module.signature.trusted = false"}, nil, nil}, - ModuleSignatureSerial: {ModuleSignatureSerial, "module certificate serial number", params.UnicodeString, []string{"module.signature.serial = '330000023241fb59996dcc4dff000000000232'"}, nil, nil}, - ModuleSignatureSubject: {ModuleSignatureSubject, "module certificate subject", params.UnicodeString, []string{"module.signature.subject contains 'Washington, Redmond, Microsoft Corporation'"}, nil, nil}, - ModuleSignatureIssuer: {ModuleSignatureIssuer, "module certificate CA", params.UnicodeString, []string{"module.signature.issuer contains 'Washington, Redmond, Microsoft Corporation'"}, nil, nil}, - ModuleSignatureAfter: {ModuleSignatureAfter, "module certificate expiration date", params.Time, []string{"module.signature.after contains '2024-02-01 00:05:42 +0000 UTC'"}, nil, nil}, - ModuleSignatureBefore: {ModuleSignatureBefore, "module certificate enrollment date", params.Time, []string{"module.signature.before contains '2024-02-01 00:05:42 +0000 UTC'"}, nil, nil}, - ModuleIsDLL: {ModuleIsDLL, "indicates if the loaded module is a DLL", params.Bool, []string{"module.is_dll'"}, nil, nil}, - ModuleIsDriver: {ModuleIsDriver, "indicates if the loaded module is a driver", params.Bool, []string{"module.is_driver'"}, nil, nil}, - ModuleIsExecutable: {ModuleIsExecutable, "indicates if the loaded module is an executable", params.Bool, []string{"module.is_exec'"}, nil, nil}, - ModuleIsDotnet: {ModuleIsDotnet, "indicates if the loaded module is a .NET assembly", params.Bool, []string{"module.pe.is_dotnet'"}, nil, nil}, - DllPath: {DllPath, "full dll path", params.UnicodeString, []string{"dll.path = 'C:\\Windows\\System32\\advapi32.dll'"}, nil, nil}, - DllPathStem: {DllPathStem, "dll path stem", params.UnicodeString, []string{"dll.path.stem = 'C:\\Windows\\System32\\advapi32'"}, nil, nil}, - DllName: {DllName, "module name", params.UnicodeString, []string{"dll.name = 'advapi32.dll'"}, nil, nil}, - DllBase: {DllBase, "the base address of process in which the DLL is loaded", params.Address, []string{"dll.base = 'a65d800000'"}, nil, nil}, - DllSize: {DllSize, "dll virtual mapped size", params.Uint32, []string{"dll.size > 1024"}, nil, nil}, - DllPID: {DllPID, "target process identifier", params.Uint32, []string{"dll.pid = 80"}, nil, nil}, - DllSignatureType: {DllSignatureType, "dll signature type", params.AnsiString, []string{"dll.signature.type != 'NONE'"}, nil, nil}, - DllSignatureLevel: {DllSignatureLevel, "dll signature level", params.AnsiString, []string{"dll.signature.level = 'AUTHENTICODE'"}, nil, nil}, - DllSignatureExists: {DllSignatureExists, "indicates if the dll is signed", params.Bool, []string{"dll.signature.exists = true"}, nil, nil}, - DllSignatureTrusted: {DllSignatureTrusted, "indicates if the dll signature is trusted", params.Bool, []string{"dll.signature.trusted = false"}, nil, nil}, - DllSignatureSerial: {DllSignatureSerial, "dll certificate serial number", params.UnicodeString, []string{"dll.signature.serial = '330000023241fb59996dcc4dff000000000232'"}, nil, nil}, - DllSignatureSubject: {DllSignatureSubject, "dll certificate subject", params.UnicodeString, []string{"dll.signature.subject contains 'Washington, Redmond, Microsoft Corporation'"}, nil, nil}, - DllSignatureIssuer: {DllSignatureIssuer, "dll certificate CA", params.UnicodeString, []string{"dll.signature.issuer contains 'Washington, Redmond, Microsoft Corporation'"}, nil, nil}, - DllSignatureAfter: {DllSignatureAfter, "moddllule certificate expiration date", params.Time, []string{"dll.signature.after contains '2024-02-01 00:05:42 +0000 UTC'"}, nil, nil}, - DllSignatureBefore: {DllSignatureBefore, "dll certificate enrollment date", params.Time, []string{"dll.signature.before contains '2024-02-01 00:05:42 +0000 UTC'"}, nil, nil}, - DllIsDotnet: {DllIsDotnet, "indicates if the loaded dll is a .NET assembly", params.Bool, []string{"dll.pe.is_dotnet'"}, nil, nil}, - - FileObject: {FileObject, "file object address", params.Uint64, []string{"file.object = 18446738026482168384"}, nil, nil}, - FilePath: {FilePath, "full file path", params.UnicodeString, []string{"file.path = 'C:\\Windows\\System32'"}, nil, nil}, - FilePathStem: {FilePathStem, "full file path without extension", params.UnicodeString, []string{"file.path.stem = 'C:\\Windows\\System32\\cmd'"}, nil, nil}, - FileName: {FileName, "full file name", params.UnicodeString, []string{"file.name contains 'mimikatz'"}, nil, nil}, - FileOperation: {FileOperation, "file operation", params.AnsiString, []string{"file.operation = 'open'"}, nil, nil}, - FileShareMask: {FileShareMask, "file share mask", params.AnsiString, []string{"file.share.mask = 'READ'"}, &Deprecation{Since: "3.1.0", Fields: []Field{FileShareMode}}, nil}, - FileShareMode: {FileShareMask, "file share mode", params.AnsiString, []string{"file.share_mode = 'DENY'"}, nil, nil}, - FileIOSize: {FileIOSize, "file I/O size", params.Uint32, []string{"file.io.size > 512"}, nil, nil}, - FileOffset: {FileOffset, "file offset", params.Uint64, []string{"file.offset = 1024"}, nil, nil}, - FileType: {FileType, "file type", params.AnsiString, []string{"file.type = 'directory'"}, nil, nil}, - FileExtension: {FileExtension, "file extension", params.AnsiString, []string{"file.extension = '.dll'"}, nil, nil}, - FileAttributes: {FileAttributes, "file attributes", params.Slice, []string{"file.attributes in ('archive', 'hidden')"}, nil, nil}, - FileStatus: {FileStatus, "file operation status message", params.UnicodeString, []string{"file.status != 'success'"}, nil, nil}, - FileViewBase: {FileViewBase, "view base address", params.Address, []string{"file.view.base = '25d42170000'"}, nil, nil}, - FileViewSize: {FileViewSize, "size of the mapped view", params.Uint64, []string{"file.view.size > 1024"}, nil, nil}, - FileViewType: {FileViewType, "type of the mapped view section", params.Enum, []string{"file.view.type = 'IMAGE'"}, nil, nil}, - FileViewProtection: {FileViewProtection, "protection rights of the section view", params.AnsiString, []string{"file.view.protection = 'READONLY'"}, nil, nil}, - FileIsDLL: {FileIsDLL, "indicates if the created file is a DLL", params.Bool, []string{"file.is_dll'"}, nil, nil}, - FileIsDriver: {FileIsDriver, "indicates if the created file is a driver", params.Bool, []string{"file.is_driver'"}, nil, nil}, - FileIsExecutable: {FileIsExecutable, "indicates if the created file is an executable", params.Bool, []string{"file.is_exec'"}, nil, nil}, - FilePID: {FilePID, "denotes the process id performing file operation", params.PID, []string{"file.pid = 4"}, nil, nil}, - FileKey: {FileKey, "uniquely identifies the file object", params.Uint64, []string{"file.key = 12446738026482168384"}, nil, nil}, - FileInfoClass: {FileInfoClass, "identifies the file information class", params.Enum, []string{"file.info_class = 'Allocation'"}, nil, nil}, - FileInfoAllocationSize: {FileInfoAllocationSize, "file allocation size", params.Uint64, []string{"file.info.allocation_size > 645400"}, nil, nil}, - FileInfoEOFSize: {FileInfoEOFSize, "file EOF size", params.Uint64, []string{"file.info.eof_size > 1000"}, nil, nil}, - FileInfoIsDispositionDeleteFile: {FileInfoIsDispositionDeleteFile, "indicates if the file is deleted when its handle is closed", params.Bool, []string{"file.info.is_disposition_file_delete = true"}, nil, nil}, - - RegistryPath: {RegistryPath, "fully qualified registry path", params.UnicodeString, []string{"registry.path = 'HKEY_LOCAL_MACHINE\\SYSTEM'"}, nil, nil}, - RegistryKeyName: {RegistryKeyName, "registry key name", params.UnicodeString, []string{"registry.key.name = 'CurrentControlSet'"}, nil, nil}, - RegistryKCB: {RegistryKCB, "registry KCB address", params.Address, []string{"registry.kcb = 'FFFFB905D60C2268'"}, nil, nil}, - RegistryValue: {RegistryValue, "registry value name", params.UnicodeString, []string{"registry.value = 'Epoch'"}, nil, nil}, - RegistryValueType: {RegistryValueType, "type of registry value", params.UnicodeString, []string{"registry.value.type = 'REG_SZ'"}, nil, nil}, - RegistryData: {RegistryData, "registry value captured data", params.Object, []string{"registry.data = '%SystemRoot%'"}, nil, nil}, - RegistryStatus: {RegistryStatus, "status of registry operation", params.UnicodeString, []string{"registry.status != 'success'"}, nil, nil}, - - NetDIP: {NetDIP, "destination IP address", params.IP, []string{"net.dip = 172.17.0.3"}, nil, nil}, - NetSIP: {NetSIP, "source IP address", params.IP, []string{"net.sip = 127.0.0.1"}, nil, nil}, - NetDport: {NetDport, "destination port", params.Uint16, []string{"net.dport in (80, 443, 8080)"}, nil, nil}, - NetSport: {NetSport, "source port", params.Uint16, []string{"net.sport != 3306"}, nil, nil}, - NetDportName: {NetDportName, "destination port name", params.AnsiString, []string{"net.dport.name = 'dns'"}, nil, nil}, - NetSportName: {NetSportName, "source port name", params.AnsiString, []string{"net.sport.name = 'http'"}, nil, nil}, - NetL4Proto: {NetL4Proto, "layer 4 protocol name", params.AnsiString, []string{"net.l4.proto = 'TCP"}, nil, nil}, - NetPacketSize: {NetPacketSize, "packet size", params.Uint32, []string{"net.size > 512"}, nil, nil}, - NetSIPNames: {NetSIPNames, "source IP names", params.Slice, []string{"net.sip.names in ('github.com.')"}, nil, nil}, - NetDIPNames: {NetDIPNames, "destination IP names", params.Slice, []string{"net.dip.names in ('github.com.')"}, nil, nil}, - - HandleID: {HandleID, "handle identifier", params.Uint16, []string{"handle.id = 24"}, nil, nil}, - HandleObject: {HandleObject, "handle object address", params.Address, []string{"handle.object = 'FFFFB905DBF61988'"}, nil, nil}, - HandleName: {HandleName, "handle name", params.UnicodeString, []string{"handle.name = '\\Device\\NamedPipe\\chrome.12644.28.105826381'"}, nil, nil}, - HandleType: {HandleType, "handle type", params.AnsiString, []string{"handle.type = 'Mutant'"}, nil, nil}, - - PeNumSections: {PeNumSections, "number of sections", params.Uint16, []string{"pe.nsections < 5"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsPeNumSections}}, nil}, - PeNumSymbols: {PeNumSymbols, "number of entries in the symbol table", params.Uint32, []string{"pe.nsymbols > 230"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsPeNumSymbols}}, nil}, - PeBaseAddress: {PeBaseAddress, "image base address", params.Address, []string{"pe.address.base = '140000000'"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsPeBaseAddress}}, nil}, - PeEntrypoint: {PeEntrypoint, "address of the entrypoint function", params.Address, []string{"pe.address.entrypoint = '20110'"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsPeEntrypoint}}, nil}, - PeSymbols: {PeSymbols, "imported symbols", params.Slice, []string{"pe.symbols in ('GetTextFaceW', 'GetProcessHeap')"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsPeSymbols}}, nil}, - PeImports: {PeImports, "imported dynamic linked libraries", params.Slice, []string{"pe.imports in ('msvcrt.dll', 'GDI32.dll'"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsPeImports}}, nil}, - - PeResources: {PeResources, "version resources", params.Map, []string{"pe.resources[FileDescription] = 'Notepad'"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsPeResources}}, &Argument{Optional: true, Pattern: "[a-zA-Z0-9_]+", ValidationFunc: func(s string) bool { - for _, c := range s { - switch { - case unicode.IsLower(c): - case unicode.IsUpper(c): - case unicode.IsNumber(c): - case c == '_': - default: - return false - } - } - return true - }}}, - - PeCompany: {PeCompany, "internal company name of the file provided at compile-time", params.UnicodeString, []string{"pe.company = 'Microsoft Corporation'"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsPeCompany}}, nil}, - PeCopyright: {PeCopyright, "copyright notice for the file emitted at compile-time", params.UnicodeString, []string{"pe.copyright = '© Microsoft Corporation'"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsPeCopyright}}, nil}, - PeDescription: {PeDescription, "internal description of the file provided at compile-time", params.UnicodeString, []string{"pe.description = 'Notepad'"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsPeDescription}}, nil}, - PeFileName: {PeFileName, "original file name supplied at compile-time", params.UnicodeString, []string{"pe.file.name = 'NOTEPAD.EXE'"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsPeFileName}}, nil}, - PeFileVersion: {PeFileVersion, "file version supplied at compile-time", params.UnicodeString, []string{"pe.file.version = '10.0.18362.693 (WinBuild.160101.0800)'"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsPeFileVersion}}, nil}, - PeProduct: {PeProduct, "internal product name of the file provided at compile-time", params.UnicodeString, []string{"pe.product = 'Microsoft® Windows® Operating System'"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsPeProduct}}, nil}, - PeProductVersion: {PeProductVersion, "internal product version of the file provided at compile-time", params.UnicodeString, []string{"pe.product.version = '10.0.18362.693'"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsPeProductVersion}}, nil}, - PeIsDLL: {PeIsDLL, "indicates if the loaded image or created file is a DLL", params.Bool, []string{"pe.is_dll'"}, &Deprecation{Since: "2.0.0", Fields: []Field{FileIsDLL, ImageIsDLL}}, nil}, - PeIsDriver: {PeIsDriver, "indicates if the loaded image or created file is a driver", params.Bool, []string{"pe.is_driver'"}, &Deprecation{Since: "2.0.0", Fields: []Field{FileIsDriver, ImageIsDriver}}, nil}, - PeIsExecutable: {PeIsExecutable, "indicates if the loaded image or created file is an executable", params.Bool, []string{"pe.is_exec'"}, &Deprecation{Since: "2.0.0", Fields: []Field{FileIsExecutable, ImageIsExecutable}}, nil}, - PeImphash: {PeImphash, "import hash", params.AnsiString, []string{"pe.impash = '5d3861c5c547f8a34e471ba273a732b2'"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsPeImphash}}, nil}, - PeIsDotnet: {PeIsDotnet, "indicates if PE contains CLR data", params.Bool, []string{"pe.is_dotnet"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsPeIsDotnet}}, nil}, - PeAnomalies: {PeAnomalies, "contains PE anomalies detected during parsing", params.Slice, []string{"pe.anomalies in ('number of sections is 0')"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsPeAnomalies}}, nil}, - PeIsSigned: {PeIsSigned, "indicates if the PE has embedded or catalog signature", params.Bool, []string{"pe.is_signed"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsSignatureExists}}, nil}, - PeIsTrusted: {PeIsTrusted, "indicates if the PE certificate chain is trusted", params.Bool, []string{"pe.is_trusted"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsSignatureTrusted}}, nil}, - PeCertSerial: {PeCertSerial, "PE certificate serial number", params.UnicodeString, []string{"pe.cert.serial = '330000023241fb59996dcc4dff000000000232'"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsSignatureSerial}}, nil}, - PeCertSubject: {PeCertSubject, "PE certificate subject", params.UnicodeString, []string{"pe.cert.subject contains 'Washington, Redmond, Microsoft Corporation'"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsSignatureSubject}}, nil}, - PeCertIssuer: {PeCertIssuer, "PE certificate CA", params.UnicodeString, []string{"pe.cert.issuer contains 'Washington, Redmond, Microsoft Corporation'"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsSignatureIssuer}}, nil}, - PeCertAfter: {PeCertAfter, "PE certificate expiration date", params.Time, []string{"pe.cert.after contains '2024-02-01 00:05:42 +0000 UTC'"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsSignatureAfter}}, nil}, - PeCertBefore: {PeCertBefore, "PE certificate enrollment date", params.Time, []string{"pe.cert.before contains '2024-02-01 00:05:42 +0000 UTC'"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsSignatureBefore}}, nil}, - PeIsModified: {PeIsModified, "indicates if disk and in-memory PE headers differ", params.Bool, []string{"pe.is_modified"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsPeIsModified}}, nil}, - - MemBaseAddress: {MemBaseAddress, "region base address", params.Address, []string{"mem.address = '211d13f2000'"}, nil, nil}, - MemRegionSize: {MemRegionSize, "region size", params.Uint64, []string{"mem.size > 438272"}, nil, nil}, - MemAllocType: {MemAllocType, "region allocation or release type", params.Flags, []string{"mem.alloc = 'COMMIT'"}, nil, nil}, - MemPageType: {MemPageType, "page type of the allocated region", params.Enum, []string{"mem.type = 'PRIVATE'"}, nil, nil}, - MemProtection: {MemProtection, "allocated region protection type", params.Enum, []string{"mem.protection = 'READWRITE'"}, nil, nil}, - MemProtectionMask: {MemProtectionMask, "allocated region protection in mask notation", params.Enum, []string{"mem.protection.mask = 'RWX'"}, nil, nil}, - - DNSName: {DNSName, "dns query name", params.UnicodeString, []string{"dns.name = 'example.org'"}, nil, nil}, - DNSRR: {DNSRR, "dns resource record type", params.AnsiString, []string{"dns.rr = 'AA'"}, nil, nil}, - DNSOptions: {DNSOptions, "dns query options", params.Flags64, []string{"dns.options in ('ADDRCONFIG', 'DUAL_ADDR')"}, nil, nil}, - DNSRcode: {DNSRR, "dns response status", params.AnsiString, []string{"dns.rcode = 'NXDOMAIN'"}, nil, nil}, - DNSAnswers: {DNSAnswers, "dns response answers", params.Slice, []string{"dns.answers in ('o.lencr.edgesuite.net', 'a1887.dscq.akamai.net')"}, nil, nil}, - - ThreadpoolPoolID: {ThreadpoolPoolID, "thread pool identifier", params.Address, []string{"threadpool.id = '20f5fc02440'"}, nil, nil}, - ThreadpoolTaskID: {ThreadpoolTaskID, "thread pool task identifier", params.Address, []string{"threadpool.task.id = '20f7ecd21f8'"}, nil, nil}, - ThreadpoolCallbackAddress: {ThreadpoolCallbackAddress, "thread pool callback address", params.Address, []string{"threadpool.callback.address = '7ff868739ed0'"}, nil, nil}, - ThreadpoolCallbackSymbol: {ThreadpoolCallbackSymbol, "thread pool callback symbol", params.UnicodeString, []string{"threadpool.callback.symbol = 'RtlDestroyQueryDebugBuffer'"}, nil, nil}, - ThreadpoolCallbackModule: {ThreadpoolCallbackModule, "thread pool module containing the callback symbol", params.UnicodeString, []string{"threadpool.callback.module contains 'ntdll.dll'"}, nil, nil}, - ThreadpoolCallbackContext: {ThreadpoolCallbackContext, "thread pool callback context address", params.Address, []string{"threadpool.callback.context = '1df41e07bd0'"}, nil, nil}, - ThreadpoolCallbackContextRip: {ThreadpoolCallbackContextRip, "thread pool callback thread context instruction pointer", params.Address, []string{"threadpool.callback.context.rip = '1df42ffc1f8'"}, nil, nil}, - ThreadpoolCallbackContextRipSymbol: {ThreadpoolCallbackContextRipSymbol, "thread pool callback thread context instruction pointer symbol", params.UnicodeString, []string{"threadpool.callback.context.rip.symbol = 'VirtualProtect'"}, nil, nil}, - ThreadpoolCallbackContextRipModule: {ThreadpoolCallbackContextRipModule, "thread pool callback thread context instruction pointer symbol module", params.UnicodeString, []string{"threadpool.callback.context.rip.module contains 'ntdll.dll'"}, nil, nil}, - ThreadpoolSubprocessTag: {ThreadpoolSubprocessTag, "thread pool service identifier", params.Address, []string{"threadpool.subprocess_tag = '10d'"}, nil, nil}, - ThreadpoolTimerDuetime: {ThreadpoolTimerDuetime, "thread pool timer due time", params.Uint64, []string{"threadpool.timer.duetime > 10"}, nil, nil}, - ThreadpoolTimerSubqueue: {ThreadpoolTimerSubqueue, "thread pool timer subqueue address", params.Address, []string{"threadpool.timer.subqueue = '1db401703e8'"}, nil, nil}, - ThreadpoolTimer: {ThreadpoolTimer, "thread pool timer address", params.Address, []string{"threadpool.timer.address = '3e8'"}, nil, nil}, - ThreadpoolTimerPeriod: {ThreadpoolTimerPeriod, "thread pool timer period", params.Uint32, []string{"threadpool.timer.period = 0'"}, nil, nil}, - ThreadpoolTimerWindow: {ThreadpoolTimerWindow, "thread pool timer tolerate period", params.Uint32, []string{"threadpool.timer.window = 0'"}, nil, nil}, - ThreadpoolTimerAbsolute: {ThreadpoolTimerAbsolute, "indicates if the thread pool timer is absolute or relative", params.Bool, []string{"threadpool.timer.is_absolute = true'"}, nil, nil}, +func platformFields(platform map[Field]FieldInfo) map[Field]FieldInfo { + fields := make(map[Field]FieldInfo, len(commonFields)+len(platform)) + for field, info := range commonFields { + fields[field] = info + } + for field, info := range platform { + fields[field] = info + } + return fields } // ArgumentOf returns argument data for the specified field. diff --git a/pkg/filter/fields/defs_linux.go b/pkg/filter/fields/defs_linux.go new file mode 100644 index 000000000..717dd8ffa --- /dev/null +++ b/pkg/filter/fields/defs_linux.go @@ -0,0 +1,36 @@ +//go:build linux + +/* + * Copyright 2026 by Mostafa Moradian + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package fields + +import "github.com/rabbitstack/fibratus/pkg/event/params" + +func platformString() params.Type { return params.String } +func platformAnsiString() params.Type { return params.String } + +var fields = platformFields(map[Field]FieldInfo{ + EvtPID: {EvtPID, "process identifier generating the event", params.Uint64, []string{"evt.pid = 6"}, nil, nil}, + EvtTID: {EvtTID, "thread identifier generating the event", params.Uint64, []string{"evt.tid = 1024"}, nil, nil}, + KevtPID: {KevtPID, "process identifier generating the event", params.Uint64, []string{"kevt.pid = 6"}, &Deprecation{Since: "3.0.0", Fields: []Field{EvtPID}}, nil}, + KevtTID: {KevtTID, "thread identifier generating the event", params.Uint64, []string{"kevt.tid = 1024"}, &Deprecation{Since: "3.0.0", Fields: []Field{EvtTID}}, nil}, + PsPid: {PsPid, "process identifier", params.Uint64, []string{"ps.pid = 1024"}, nil, nil}, + PsPpid: {PsPpid, "parent process identifier", params.Uint64, []string{"ps.ppid = 45"}, nil, nil}, + PsParentPid: {PsParentPid, "parent process id", params.Uint64, []string{"ps.parent.pid = 4"}, nil, nil}, +}) diff --git a/pkg/filter/fields/defs_linux_test.go b/pkg/filter/fields/defs_linux_test.go new file mode 100644 index 000000000..22eeaf939 --- /dev/null +++ b/pkg/filter/fields/defs_linux_test.go @@ -0,0 +1,42 @@ +//go:build linux + +/* + * Copyright 2026 by Mostafa Moradian + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package fields + +import ( + "testing" + + "github.com/rabbitstack/fibratus/pkg/event/params" + "github.com/stretchr/testify/require" +) + +func TestLinuxFields(t *testing.T) { + require.True(t, IsField(string(EvtName))) + require.True(t, IsField(string(PsName))) + require.True(t, IsField(string(PsParentExe))) + require.Equal(t, params.String, EvtName.Type()) + require.Equal(t, params.String, PsName.Type()) + require.Equal(t, params.Uint64, EvtPID.Type()) + require.Equal(t, params.Uint64, EvtTID.Type()) + require.Equal(t, params.Uint64, PsPid.Type()) + require.False(t, IsField(string(PsComm))) + require.False(t, IsField(string(RegistryPath))) + require.False(t, IsField(string(PeEntrypoint))) +} diff --git a/pkg/filter/fields/defs_windows.go b/pkg/filter/fields/defs_windows.go new file mode 100644 index 000000000..14faab085 --- /dev/null +++ b/pkg/filter/fields/defs_windows.go @@ -0,0 +1,322 @@ +//go:build windows + +/* + * Copyright 2019-2020 by Nedim Sabic Sabic + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package fields + +import ( + "unicode" + + "github.com/rabbitstack/fibratus/pkg/event/params" +) + +func platformString() params.Type { return params.UnicodeString } +func platformAnsiString() params.Type { return params.AnsiString } + +var fields = platformFields(map[Field]FieldInfo{ + EvtPID: {EvtPID, "process identifier generating the event", params.Uint32, []string{"evt.pid = 6"}, nil, nil}, + EvtTID: {EvtTID, "thread identifier generating the event", params.Uint32, []string{"evt.tid = 1024"}, nil, nil}, + KevtPID: {KevtPID, "process identifier generating the event", params.Uint32, []string{"kevt.pid = 6"}, &Deprecation{Since: "3.0.0", Fields: []Field{EvtPID}}, nil}, + KevtTID: {KevtTID, "thread identifier generating the event", params.Uint32, []string{"kevt.tid = 1024"}, &Deprecation{Since: "3.0.0", Fields: []Field{EvtTID}}, nil}, + PsPid: {PsPid, "process identifier", params.PID, []string{"ps.pid = 1024"}, nil, nil}, + PsPpid: {PsPpid, "parent process identifier", params.PID, []string{"ps.ppid = 45"}, nil, nil}, + PsParentPid: {PsParentPid, "parent process id", params.Uint32, []string{"ps.parent.pid = 4"}, nil, nil}, + EvtIsDirectSyscall: {EvtIsDirectSyscall, "indicates if the event is performing a direct syscall", params.Bool, []string{"evt.is_direct_syscall = true"}, nil, nil}, + EvtIsIndirectSyscall: {EvtIsIndirectSyscall, "indicates if the event is performing an indirect syscall", params.Bool, []string{"evt.is_indirect_syscall = true"}, nil, nil}, + PsComm: {PsComm, "process command line", params.UnicodeString, []string{"ps.comm contains 'java'"}, &Deprecation{Since: "1.10.0", Fields: []Field{PsCmdline}}, nil}, + PsSID: {PsSID, "security identifier under which this process is run", params.UnicodeString, []string{"ps.sid contains 'SYSTEM'"}, nil, nil}, + PsSessionID: {PsSessionID, "unique identifier for the current session", params.Int16, []string{"ps.sessionid = 1"}, nil, nil}, + PsDomain: {PsDomain, "process domain", params.UnicodeString, []string{"ps.domain contains 'SERVICE'"}, nil, nil}, + PsHandleNames: {PsHandleNames, "allocated process handle names", params.Slice, []string{"ps.handles in ('\\BaseNamedObjects\\__ComCatalogCache__')"}, nil, nil}, + PsHandleTypes: {PsHandleTypes, "allocated process handle types", params.Slice, []string{"ps.handle.types in ('Key', 'Mutant', 'Section')"}, nil, nil}, + PsDTB: {PsDTB, "process directory table base address", params.Address, []string{"ps.dtb = '7ffe0000'"}, nil, nil}, + PsModuleNames: {PsModuleNames, "modules loaded by the process", params.Slice, []string{"ps.modules in ('crypt32.dll', 'xul.dll')"}, nil, nil}, + PsParentComm: {PsParentComm, "parent process command line", params.UnicodeString, []string{"ps.parent.comm contains 'java'"}, &Deprecation{Since: "1.10.0", Fields: []Field{PsParentCmdline}}, nil}, + PsParentArgs: {PsParentArgs, "parent process command line arguments", params.Slice, []string{"ps.parent.args in ('/cdir', '/-C')"}, nil, nil}, + PsParentCwd: {PsParentCwd, "parent process current working directory", params.UnicodeString, []string{"ps.parent.cwd = 'C:\\Temp'"}, nil, nil}, + PsParentSID: {PsParentSID, "security identifier under which the parent process is run", params.UnicodeString, []string{"ps.parent.sid contains 'SYSTEM'"}, nil, nil}, + PsParentDomain: {PsParentDomain, "parent process domain", params.UnicodeString, []string{"ps.parent.domain contains 'SERVICE'"}, nil, nil}, + PsParentUsername: {PsParentUsername, "parent process username", params.UnicodeString, []string{"ps.parent.username contains 'system'"}, nil, nil}, + PsParentSessionID: {PsParentSessionID, "unique identifier for the current session of parent process", params.Int16, []string{"ps.parent.sessionid = 1"}, nil, nil}, + PsParentEnvs: {PsParentEnvs, "parent process environment variables", params.Slice, []string{"ps.parent.envs in ('MOZ_CRASHREPORTER_DATA_DIRECTORY')"}, nil, nil}, + PsParentHandles: {PsParentHandles, "allocated parent process handle names", params.Slice, []string{"ps.parent.handles in ('\\BaseNamedObjects\\__ComCatalogCache__')"}, nil, nil}, + PsParentHandleTypes: {PsParentHandleTypes, "allocated parent process handle types", params.Slice, []string{"ps.parent.handle.types in ('File', 'SymbolicLink')"}, nil, nil}, + PsParentDTB: {PsParentDTB, "parent process directory table base address", params.Address, []string{"ps.parent.dtb = '7ffe0000'"}, nil, nil}, + PsAccessMask: {PsAccessMask, "process desired access rights", params.AnsiString, []string{"ps.access.mask = '0x1400'"}, nil, nil}, + PsAccessMaskNames: {PsAccessMaskNames, "process desired access rights as a string list", params.Slice, []string{"ps.access.mask.names in ('SUSPEND_RESUME')"}, nil, nil}, + PsAccessStatus: {PsAccessStatus, "process access status", params.UnicodeString, []string{"ps.access.status = 'access is denied.'"}, nil, nil}, + PsUUID: {PsUUID, "unique process identifier", params.Uint64, []string{"ps.uuid > 6000054355"}, nil, nil}, + PsParentUUID: {PsParentUUID, "unique parent process identifier", params.Uint64, []string{"ps.parent.uuid > 6000054355"}, nil, nil}, + PsIsWOW64Field: {PsIsWOW64Field, "indicates if the process generating the event is a 32-bit process created in 64-bit Windows system", params.Bool, []string{"ps.is_wow64"}, nil, nil}, + PsIsPackagedField: {PsIsPackagedField, "indicates if the process generating the event is packaged with the MSIX technology", params.Bool, []string{"ps.is_packaged"}, nil, nil}, + PsIsProtectedField: {PsIsProtectedField, "indicates if the process generating the event is a protected process", params.Bool, []string{"ps.is_protected"}, nil, nil}, + PsParentIsWOW64Field: {PsParentIsWOW64Field, "indicates if the parent process generating the event is a 32-bit process created in 64-bit Windows system", params.Bool, []string{"ps.parent.is_wow64"}, nil, nil}, + PsParentIsPackagedField: {PsParentIsPackagedField, "indicates if the parent process generating the event is packaged with the MSIX technology", params.Bool, []string{"ps.parent.is_packaged"}, nil, nil}, + PsParentIsProtectedField: {PsParentIsProtectedField, "indicates if the the parent process generating the event is a protected process", params.Bool, []string{"ps.parent.is_protected"}, nil, nil}, + PsAncestor: {PsAncestor, "the process ancestor name", params.UnicodeString, []string{"ps.ancestor[1] = 'svchost.exe'", "ps.ancestor in ('winword.exe')"}, nil, &Argument{Optional: true, Pattern: "[0-9]+", ValidationFunc: isNumber}}, + PsTokenIntegrityLevel: {PsTokenIntegrityLevel, "process token integrity level", params.UnicodeString, []string{"ps.token.integrity_level = 'SYSTEM'"}, nil, nil}, + PsTokenIsElevated: {PsTokenIsElevated, "indicates if the process token is elevated", params.Bool, []string{"ps.token.is_elevated = true"}, nil, nil}, + PsTokenElevationType: {PsTokenElevationType, "process token elevation type", params.AnsiString, []string{"ps.token.elevation_type = 'LIMITED'"}, nil, nil}, + PsParentTokenIntegrityLevel: {PsParentTokenIntegrityLevel, "parent process token integrity level", params.UnicodeString, []string{"ps.parent.token.integrity_level = 'HIGH'"}, nil, nil}, + PsParentTokenIsElevated: {PsParentTokenIsElevated, "indicates if the parent process token is elevated", params.Bool, []string{"ps.parent.token.is_elevated = true"}, nil, nil}, + PsParentTokenElevationType: {PsParentTokenElevationType, "parent process token elevation type", params.AnsiString, []string{"ps.parent.token.elevation_type = 'LIMITED'"}, nil, nil}, + PsSignatureExists: {PsSignatureExists, "indicates if the process executable has a valid signature", params.Bool, []string{"ps.signature.exists"}, nil, nil}, + PsSignatureTrusted: {PsSignatureTrusted, "indicates if the process executable signature certificate chain is trusted", params.Bool, []string{"ps.signature.trusted"}, nil, nil}, + PsSignatureSerial: {PsSignatureSerial, "represents signature serial number", params.UnicodeString, []string{"ps.signature.serial = '330000023241fb59996dcc4dff000000000232'"}, nil, nil}, + PsSignatureSubject: {PsSignatureSubject, "represents signature subject", params.UnicodeString, []string{"ps.signature.subject contains 'Washington, Redmond, Microsoft Corporation'"}, nil, nil}, + PsSignatureIssuer: {PsSignatureIssuer, "represents signature CA", params.UnicodeString, []string{"ps.signature.issuer contains 'Washington, Redmond, Microsoft Corporation'"}, nil, nil}, + PsSignatureAfter: {PsSignatureAfter, "represents certificate expiration date", params.Time, []string{"ps.signature.after contains '2024-02-01 00:05:42 +0000 UTC'"}, nil, nil}, + PsSignatureBefore: {PsSignatureBefore, "represents certificate enrollment date", params.Time, []string{"ps.signature.before contains '2024-02-01 00:05:42 +0000 UTC'"}, nil, nil}, + PsPeNumSections: {PsPeNumSections, "number of PE sections", params.Uint16, []string{"ps.pe.nsections < 5"}, nil, nil}, + PsPeNumSymbols: {PsPeNumSymbols, "number of entries in the symbol table", params.Uint32, []string{"ps.pe.nsymbols > 230"}, nil, nil}, + PsPeBaseAddress: {PsPeBaseAddress, "executable base address", params.Address, []string{"ps.pe.address.base = '140000000'"}, nil, nil}, + PsPeEntrypoint: {PsPeEntrypoint, "address of the entrypoint function", params.Address, []string{"ps.pe.address.entrypoint = '20110'"}, nil, nil}, + PsPeSymbols: {PsPeSymbols, "imported symbols", params.Slice, []string{"ps.pe.symbols in ('GetTextFaceW', 'GetProcessHeap')"}, nil, nil}, + PsPeImports: {PsPeImports, "imported dynamic linked libraries", params.Slice, []string{"ps.pe.imports in ('msvcrt.dll', 'GDI32.dll'"}, nil, nil}, + PsPeResources: {PsPeResources, "version resources", params.Map, []string{"ps.pe.resources[FileDescription] = 'Notepad'"}, nil, &Argument{Optional: true, Pattern: "[a-zA-Z0-9_]+", ValidationFunc: func(s string) bool { + for _, c := range s { + switch { + case unicode.IsLower(c): + case unicode.IsUpper(c): + case unicode.IsNumber(c): + case c == '_': + default: + return false + } + } + return true + }}}, + PsPeCompany: {PsPeCompany, "internal company name of the file provided at compile-time", params.UnicodeString, []string{"ps.pe.company = 'Microsoft Corporation'"}, nil, nil}, + PsPeCopyright: {PsPeCopyright, "copyright notice for the file emitted at compile-time", params.UnicodeString, []string{"ps.pe.copyright = '© Microsoft Corporation'"}, nil, nil}, + PsPeDescription: {PsPeDescription, "internal description of the file provided at compile-time", params.UnicodeString, []string{"ps.pe.description = 'Notepad'"}, nil, nil}, + PsPeFileName: {PsPeFileName, "original file name supplied at compile-time", params.UnicodeString, []string{"ps.pe.file.name = 'NOTEPAD.EXE'"}, nil, nil}, + PsPeFileVersion: {PsPeFileVersion, "file version supplied at compile-time", params.UnicodeString, []string{"ps.pe.file.version = '10.0.18362.693 (WinBuild.160101.0800)'"}, nil, nil}, + PsPeProduct: {PsPeProduct, "internal product name of the file provided at compile-time", params.UnicodeString, []string{"ps.pe.product = 'Microsoft® Windows® Operating System'"}, nil, nil}, + PsPeProductVersion: {PsPeProductVersion, "internal product version of the file provided at compile-time", params.UnicodeString, []string{"ps.pe.product.version = '10.0.18362.693'"}, nil, nil}, + PsPeImphash: {PsPeImphash, "import hash", params.AnsiString, []string{"pe.impash = '5d3861c5c547f8a34e471ba273a732b2'"}, nil, nil}, + PsPeIsDotnet: {PsPeIsDotnet, "indicates if PE contains CLR data", params.Bool, []string{"ps.pe.is_dotnet"}, nil, nil}, + PsPeAnomalies: {PsPeAnomalies, "contains PE anomalies detected during parsing", params.Slice, []string{"ps.pe.anomalies in ('number of sections is 0')"}, nil, nil}, + PsPeIsModified: {PsPeIsModified, "indicates if disk and in-memory PE headers differ", params.Bool, []string{"ps.pe.is_modified"}, nil, nil}, + ThreadBasePrio: {ThreadBasePrio, "scheduler priority of the thread", params.Int8, []string{"thread.prio = 5"}, nil, nil}, + ThreadIOPrio: {ThreadIOPrio, "I/O priority hint for scheduling I/O operations", params.Int8, []string{"thread.io.prio = 4"}, nil, nil}, + ThreadPagePrio: {ThreadPagePrio, "memory page priority hint for memory pages accessed by the thread", params.Int8, []string{"thread.page.prio = 12"}, nil, nil}, + ThreadKstackBase: {ThreadKstackBase, "base address of the thread's kernel space stack", params.Address, []string{"thread.kstack.base = 'a65d800000'"}, nil, nil}, + ThreadKstackLimit: {ThreadKstackLimit, "limit of the thread's kernel space stack", params.Address, []string{"thread.kstack.limit = 'a85d800000'"}, nil, nil}, + ThreadUstackBase: {ThreadUstackBase, "base address of the thread's user space stack", params.Address, []string{"thread.ustack.base = '7ffe0000'"}, nil, nil}, + ThreadUstackLimit: {ThreadUstackLimit, "limit of the thread's user space stack", params.Address, []string{"thread.ustack.limit = '8ffe0000'"}, nil, nil}, + ThreadEntrypoint: {ThreadEntrypoint, "starting address of the function to be executed by the thread", params.Address, []string{"thread.entrypoint = '7efe0000'"}, &Deprecation{Since: "2.3.0", Fields: []Field{ThreadStartAddress}}, nil}, + ThreadStartAddress: {ThreadStartAddress, "thread start address", params.Address, []string{"thread.start_address = '7efe0000'"}, nil, nil}, + ThreadStartAddressSymbol: {ThreadStartAddressSymbol, "thread start address symbol", params.UnicodeString, []string{"thread.start_address.symbol = 'LoadModule'"}, nil, nil}, + ThreadStartAddressModule: {ThreadStartAddressModule, "thread start address module", params.UnicodeString, []string{"thread.start_address.module endswith 'kernel32.dll'"}, nil, nil}, + ThreadPID: {ThreadPID, "the process identifier where the thread is created", params.Uint32, []string{"evt.pid != thread.pid"}, nil, nil}, + ThreadTEB: {ThreadTEB, "the base address of the thread environment block", params.Address, []string{"thread.teb_address = '8f30893000'"}, nil, nil}, + ThreadAccessMask: {ThreadAccessMask, "thread desired access rights", params.AnsiString, []string{"thread.access.mask = '0x1fffff'"}, nil, nil}, + ThreadAccessMaskNames: {ThreadAccessMaskNames, "thread desired access rights as a string list", params.Slice, []string{"thread.access.mask.names in ('IMPERSONATE')"}, nil, nil}, + ThreadAccessStatus: {ThreadAccessStatus, "thread access status", params.UnicodeString, []string{"thread.access.status = 'success'"}, nil, nil}, + ThreadCallstackSummary: {ThreadCallstackSummary, "callstack summary", params.UnicodeString, []string{"thread.callstack.summary contains 'ntdll.dll|KERNELBASE.dll'"}, nil, nil}, + ThreadCallstackKernelSummary: {ThreadCallstackKernelSummary, "kernel thread callstack summary", params.UnicodeString, []string{"thread.callstack.kernel_summary contains 'fileinfo.sys|ntoskrnl.exe|FLTMGR.SYS|ntoskrnl.exe'"}, nil, nil}, + ThreadCallstackDetail: {ThreadCallstackDetail, "detailed information of each stack frame", params.UnicodeString, []string{"thread.callstack.detail contains 'KERNELBASE.dll!CreateProcessW'"}, nil, nil}, + ThreadCallstackModules: {ThreadCallstackModules, "list of modules comprising the callstack", params.Slice, []string{"thread.callstack.modules in ('C:\\WINDOWS\\System32\\KERNELBASE.dll')", "base(thread.callstack.modules[7]) = 'ntdll.dll'"}, nil, &Argument{Optional: true, Pattern: "[0-9]+", ValidationFunc: isNumber}}, + ThreadCallstackSymbols: {ThreadCallstackSymbols, "list of symbols comprising the callstack", params.Slice, []string{"thread.callstack.symbols in ('ntdll.dll!NtCreateProcess')", "thread.callstack.symbols[3] = 'ntdll!NtCreateProcess'"}, nil, &Argument{Optional: true, Pattern: "[0-9]+", ValidationFunc: isNumber}}, + ThreadCallstackAllocationSizes: {ThreadCallstackAllocationSizes, "allocation sizes of private pages", params.Slice, []string{"thread.callstack.allocation_sizes > 10000"}, nil, nil}, + ThreadCallstackProtections: {ThreadCallstackProtections, "page protections masks of each frame", params.Slice, []string{"thread.callstack.protections in ('RWX', 'WX')"}, nil, nil}, + ThreadCallstackCallsiteLeadingAssembly: {ThreadCallstackCallsiteLeadingAssembly, "callsite leading assembly instructions", params.Slice, []string{"thread.callstack.callsite_leading_assembly in ('mov r10,rcx', 'syscall')"}, nil, nil}, + ThreadCallstackCallsiteTrailingAssembly: {ThreadCallstackCallsiteTrailingAssembly, "callsite trailing assembly instructions", params.Slice, []string{"thread.callstack.callsite_trailing_assembly in ('add esp, 0xab')"}, nil, nil}, + ThreadCallstackIsUnbacked: {ThreadCallstackIsUnbacked, "indicates if the callstack contains unbacked regions", params.Bool, []string{"thread.callstack.is_unbacked"}, nil, nil}, + ThreadCallstackAddresses: {ThreadCallstackAddresses, "list of all stack return addresses", params.Slice, []string{"thread.callstack.addresses in ('7ffb5c1d0396')"}, nil, nil}, + ThreadCallstackFinalUserModuleName: {ThreadCallstackFinalUserModuleName, "final user space stack frame module name", params.UnicodeString, []string{"thread.callstack.final_user_module.name != 'ntdll.dll'"}, nil, nil}, + ThreadCallstackFinalUserModulePath: {ThreadCallstackFinalUserModulePath, "final user space stack frame module path", params.UnicodeString, []string{"thread.callstack.final_user_module.path imatches '?:\\Windows\\System32\\ntdll.dll'"}, nil, nil}, + ThreadCallstackFinalUserSymbolName: {ThreadCallstackFinalUserSymbolName, "final user space stack symbol name", params.UnicodeString, []string{"thread.callstack.final_user_symbol.name imatches 'CreateProcess*'"}, nil, nil}, + ThreadCallstackFinalKernelModuleName: {ThreadCallstackFinalKernelModuleName, "final kernel space stack frame module name", params.UnicodeString, []string{"thread.callstack.final_kernel_module.name = 'FLTMGR.SYS'"}, nil, nil}, + ThreadCallstackFinalKernelModulePath: {ThreadCallstackFinalKernelModulePath, "final kernel space stack frame module path", params.UnicodeString, []string{"thread.callstack.final_kernel_module.path imatches '?:\\WINDOWS\\System32\\drivers\\FLTMGR.SYS'"}, nil, nil}, + ThreadCallstackFinalKernelSymbolName: {ThreadCallstackFinalKernelSymbolName, "final kernel space stack symbol name", params.UnicodeString, []string{"thread.callstack.final_kernel_symbol.name = 'FltGetStreamContext'"}, nil, nil}, + ThreadCallstackFinalUserModuleSignatureExists: {ThreadCallstackFinalUserModuleSignatureExists, "signature status of the final user space stack frame module", params.Bool, []string{"thread.callstack.final_user_module.signature.exists = true"}, nil, nil}, + ThreadCallstackFinalUserModuleSignatureTrusted: {ThreadCallstackFinalUserModuleSignatureTrusted, "signature trust status of the final user space stack frame module", params.Bool, []string{"thread.callstack.final_user_module.signature.trusted = true"}, nil, nil}, + ThreadCallstackFinalUserModuleSignatureIssuer: {ThreadCallstackFinalUserModuleSignatureIssuer, "final user space stack frame module signature certificate issuer", params.UnicodeString, []string{"thread.callstack.final_user_module.signature.issuer imatches '*Microsoft Corporation*'"}, nil, nil}, + ThreadCallstackFinalUserModuleSignatureSubject: {ThreadCallstackFinalUserModuleSignatureSubject, "final user space stack frame module signature certificate subject", params.UnicodeString, []string{"thread.callstack.final_user_module.signature.subject imatches '*Microsoft Windows*'"}, nil, nil}, + ImagePath: {ImagePath, "full image path", params.UnicodeString, []string{"image.path = 'C:\\Windows\\System32\\advapi32.dll'"}, &Deprecation{Since: "3.0.0", Fields: []Field{ModulePath}}, nil}, + ImageName: {ImageName, "image name", params.UnicodeString, []string{"image.name = 'advapi32.dll'"}, &Deprecation{Since: "3.0.0", Fields: []Field{ModuleName}}, nil}, + ImageBase: {ImageBase, "the base address of process in which the image is loaded", params.Address, []string{"image.base.address = 'a65d800000'"}, &Deprecation{Since: "3.0.0", Fields: []Field{ModuleBase}}, nil}, + ImageChecksum: {ImageChecksum, "image checksum", params.Uint32, []string{"image.checksum = 746424"}, &Deprecation{Since: "3.0.0", Fields: []Field{ModuleChecksum}}, nil}, + ImageSize: {ImageSize, "image size", params.Uint32, []string{"image.size > 1024"}, &Deprecation{Since: "3.0.0", Fields: []Field{ModuleSize}}, nil}, + ImageDefaultAddress: {ImageDefaultAddress, "default image address", params.Address, []string{"image.default.address = '7efe0000'"}, &Deprecation{Since: "3.0.0", Fields: []Field{ModuleDefaultAddress}}, nil}, + ImagePID: {ImagePID, "target process identifier", params.Uint32, []string{"image.pid = 80"}, &Deprecation{Since: "3.0.0", Fields: []Field{ModulePID}}, nil}, + ImageSignatureType: {ImageSignatureType, "image signature type", params.AnsiString, []string{"image.signature.type != 'NONE'"}, &Deprecation{Since: "3.0.0", Fields: []Field{ModuleSignatureType}}, nil}, + ImageSignatureLevel: {ImageSignatureLevel, "image signature level", params.AnsiString, []string{"image.signature.level = 'AUTHENTICODE'"}, &Deprecation{Since: "3.0.0", Fields: []Field{ModuleSignatureLevel}}, nil}, + ImageCertSerial: {ImageCertSerial, "image certificate serial number", params.UnicodeString, []string{"image.cert.serial = '330000023241fb59996dcc4dff000000000232'"}, &Deprecation{Since: "3.0.0", Fields: []Field{ModuleSignatureSerial}}, nil}, + ImageCertSubject: {ImageCertSubject, "image certificate subject", params.UnicodeString, []string{"image.cert.subject contains 'Washington, Redmond, Microsoft Corporation'"}, &Deprecation{Since: "3.0.0", Fields: []Field{ModuleSignatureSubject}}, nil}, + ImageCertIssuer: {ImageCertIssuer, "image certificate CA", params.UnicodeString, []string{"image.cert.issuer contains 'Washington, Redmond, Microsoft Corporation'"}, &Deprecation{Since: "3.0.0", Fields: []Field{ModuleSignatureIssuer}}, nil}, + ImageCertAfter: {ImageCertAfter, "image certificate expiration date", params.Time, []string{"image.cert.after contains '2024-02-01 00:05:42 +0000 UTC'"}, &Deprecation{Since: "3.0.0", Fields: []Field{ModuleSignatureAfter}}, nil}, + ImageCertBefore: {ImageCertBefore, "image certificate enrollment date", params.Time, []string{"image.cert.before contains '2024-02-01 00:05:42 +0000 UTC'"}, &Deprecation{Since: "3.0.0", Fields: []Field{ModuleSignatureBefore}}, nil}, + ImageIsDLL: {ImageIsDLL, "indicates if the loaded image is a DLL", params.Bool, []string{"image.is_dll'"}, &Deprecation{Since: "3.0.0", Fields: []Field{ModuleIsDLL}}, nil}, + ImageIsDriver: {ImageIsDriver, "indicates if the loaded image is a driver", params.Bool, []string{"image.is_driver'"}, &Deprecation{Since: "3.0.0", Fields: []Field{ModuleIsDriver}}, nil}, + ImageIsExecutable: {ImageIsExecutable, "indicates if the loaded image is an executable", params.Bool, []string{"image.is_exec'"}, &Deprecation{Since: "3.0.0", Fields: []Field{ModuleIsExecutable}}, nil}, + ImageIsDotnet: {ImageIsDotnet, "indicates if the loaded image is a .NET assembly", params.Bool, []string{"image.is_dotnet'"}, &Deprecation{Since: "3.0.0", Fields: []Field{ModuleIsDotnet}}, nil}, + ModulePath: {ModulePath, "full module path", params.UnicodeString, []string{"module.path = 'C:\\Windows\\System32\\advapi32.dll'"}, nil, nil}, + ModulePathStem: {ModulePathStem, "module path stem", params.UnicodeString, []string{"module.path.stem = 'C:\\Windows\\System32\\advapi32'"}, nil, nil}, + ModuleName: {ModuleName, "module name", params.UnicodeString, []string{"module.name = 'advapi32.dll'"}, nil, nil}, + ModuleBase: {ModuleBase, "the base address of process in which the module is loaded", params.Address, []string{"module.base.address = 'a65d800000'"}, nil, nil}, + ModuleChecksum: {ModuleChecksum, "module checksum", params.Uint32, []string{"module.checksum = 746424"}, nil, nil}, + ModuleSize: {ModuleSize, "module size", params.Uint32, []string{"module.size > 1024"}, nil, nil}, + ModuleDefaultAddress: {ModuleDefaultAddress, "default module address", params.Address, []string{"module.default_address = '7efe0000'"}, nil, nil}, + ModulePID: {ModulePID, "target process identifier", params.Uint32, []string{"module.pid = 80"}, nil, nil}, + ModuleSignatureType: {ModuleSignatureType, "module signature type", params.AnsiString, []string{"module.signature.type != 'NONE'"}, nil, nil}, + ModuleSignatureLevel: {ModuleSignatureLevel, "module signature level", params.AnsiString, []string{"module.signature.level = 'AUTHENTICODE'"}, nil, nil}, + ModuleSignatureExists: {ModuleSignatureExists, "indicates if the module is signed", params.Bool, []string{"module.signature.exists = true"}, nil, nil}, + ModuleSignatureTrusted: {ModuleSignatureTrusted, "indicates if the module signature is trusted", params.Bool, []string{"module.signature.trusted = false"}, nil, nil}, + ModuleSignatureSerial: {ModuleSignatureSerial, "module certificate serial number", params.UnicodeString, []string{"module.signature.serial = '330000023241fb59996dcc4dff000000000232'"}, nil, nil}, + ModuleSignatureSubject: {ModuleSignatureSubject, "module certificate subject", params.UnicodeString, []string{"module.signature.subject contains 'Washington, Redmond, Microsoft Corporation'"}, nil, nil}, + ModuleSignatureIssuer: {ModuleSignatureIssuer, "module certificate CA", params.UnicodeString, []string{"module.signature.issuer contains 'Washington, Redmond, Microsoft Corporation'"}, nil, nil}, + ModuleSignatureAfter: {ModuleSignatureAfter, "module certificate expiration date", params.Time, []string{"module.signature.after contains '2024-02-01 00:05:42 +0000 UTC'"}, nil, nil}, + ModuleSignatureBefore: {ModuleSignatureBefore, "module certificate enrollment date", params.Time, []string{"module.signature.before contains '2024-02-01 00:05:42 +0000 UTC'"}, nil, nil}, + ModuleIsDLL: {ModuleIsDLL, "indicates if the loaded module is a DLL", params.Bool, []string{"module.is_dll'"}, nil, nil}, + ModuleIsDriver: {ModuleIsDriver, "indicates if the loaded module is a driver", params.Bool, []string{"module.is_driver'"}, nil, nil}, + ModuleIsExecutable: {ModuleIsExecutable, "indicates if the loaded module is an executable", params.Bool, []string{"module.is_exec'"}, nil, nil}, + ModuleIsDotnet: {ModuleIsDotnet, "indicates if the loaded module is a .NET assembly", params.Bool, []string{"module.pe.is_dotnet'"}, nil, nil}, + DllPath: {DllPath, "full dll path", params.UnicodeString, []string{"dll.path = 'C:\\Windows\\System32\\advapi32.dll'"}, nil, nil}, + DllPathStem: {DllPathStem, "dll path stem", params.UnicodeString, []string{"dll.path.stem = 'C:\\Windows\\System32\\advapi32'"}, nil, nil}, + DllName: {DllName, "module name", params.UnicodeString, []string{"dll.name = 'advapi32.dll'"}, nil, nil}, + DllBase: {DllBase, "the base address of process in which the DLL is loaded", params.Address, []string{"dll.base = 'a65d800000'"}, nil, nil}, + DllSize: {DllSize, "dll virtual mapped size", params.Uint32, []string{"dll.size > 1024"}, nil, nil}, + DllPID: {DllPID, "target process identifier", params.Uint32, []string{"dll.pid = 80"}, nil, nil}, + DllSignatureType: {DllSignatureType, "dll signature type", params.AnsiString, []string{"dll.signature.type != 'NONE'"}, nil, nil}, + DllSignatureLevel: {DllSignatureLevel, "dll signature level", params.AnsiString, []string{"dll.signature.level = 'AUTHENTICODE'"}, nil, nil}, + DllSignatureExists: {DllSignatureExists, "indicates if the dll is signed", params.Bool, []string{"dll.signature.exists = true"}, nil, nil}, + DllSignatureTrusted: {DllSignatureTrusted, "indicates if the dll signature is trusted", params.Bool, []string{"dll.signature.trusted = false"}, nil, nil}, + DllSignatureSerial: {DllSignatureSerial, "dll certificate serial number", params.UnicodeString, []string{"dll.signature.serial = '330000023241fb59996dcc4dff000000000232'"}, nil, nil}, + DllSignatureSubject: {DllSignatureSubject, "dll certificate subject", params.UnicodeString, []string{"dll.signature.subject contains 'Washington, Redmond, Microsoft Corporation'"}, nil, nil}, + DllSignatureIssuer: {DllSignatureIssuer, "dll certificate CA", params.UnicodeString, []string{"dll.signature.issuer contains 'Washington, Redmond, Microsoft Corporation'"}, nil, nil}, + DllSignatureAfter: {DllSignatureAfter, "moddllule certificate expiration date", params.Time, []string{"dll.signature.after contains '2024-02-01 00:05:42 +0000 UTC'"}, nil, nil}, + DllSignatureBefore: {DllSignatureBefore, "dll certificate enrollment date", params.Time, []string{"dll.signature.before contains '2024-02-01 00:05:42 +0000 UTC'"}, nil, nil}, + DllIsDotnet: {DllIsDotnet, "indicates if the loaded dll is a .NET assembly", params.Bool, []string{"dll.pe.is_dotnet'"}, nil, nil}, + FileObject: {FileObject, "file object address", params.Uint64, []string{"file.object = 18446738026482168384"}, nil, nil}, + FilePath: {FilePath, "full file path", params.UnicodeString, []string{"file.path = 'C:\\Windows\\System32'"}, nil, nil}, + FilePathStem: {FilePathStem, "full file path without extension", params.UnicodeString, []string{"file.path.stem = 'C:\\Windows\\System32\\cmd'"}, nil, nil}, + FileName: {FileName, "full file name", params.UnicodeString, []string{"file.name contains 'mimikatz'"}, nil, nil}, + FileOperation: {FileOperation, "file operation", params.AnsiString, []string{"file.operation = 'open'"}, nil, nil}, + FileShareMask: {FileShareMask, "file share mask", params.AnsiString, []string{"file.share.mask = 'READ'"}, &Deprecation{Since: "3.1.0", Fields: []Field{FileShareMode}}, nil}, + FileShareMode: {FileShareMask, "file share mode", params.AnsiString, []string{"file.share_mode = 'DENY'"}, nil, nil}, + FileIOSize: {FileIOSize, "file I/O size", params.Uint32, []string{"file.io.size > 512"}, nil, nil}, + FileOffset: {FileOffset, "file offset", params.Uint64, []string{"file.offset = 1024"}, nil, nil}, + FileType: {FileType, "file type", params.AnsiString, []string{"file.type = 'directory'"}, nil, nil}, + FileExtension: {FileExtension, "file extension", params.AnsiString, []string{"file.extension = '.dll'"}, nil, nil}, + FileAttributes: {FileAttributes, "file attributes", params.Slice, []string{"file.attributes in ('archive', 'hidden')"}, nil, nil}, + FileStatus: {FileStatus, "file operation status message", params.UnicodeString, []string{"file.status != 'success'"}, nil, nil}, + FileViewBase: {FileViewBase, "view base address", params.Address, []string{"file.view.base = '25d42170000'"}, nil, nil}, + FileViewSize: {FileViewSize, "size of the mapped view", params.Uint64, []string{"file.view.size > 1024"}, nil, nil}, + FileViewType: {FileViewType, "type of the mapped view section", params.Enum, []string{"file.view.type = 'IMAGE'"}, nil, nil}, + FileViewProtection: {FileViewProtection, "protection rights of the section view", params.AnsiString, []string{"file.view.protection = 'READONLY'"}, nil, nil}, + FileIsDLL: {FileIsDLL, "indicates if the created file is a DLL", params.Bool, []string{"file.is_dll'"}, nil, nil}, + FileIsDriver: {FileIsDriver, "indicates if the created file is a driver", params.Bool, []string{"file.is_driver'"}, nil, nil}, + FileIsExecutable: {FileIsExecutable, "indicates if the created file is an executable", params.Bool, []string{"file.is_exec'"}, nil, nil}, + FilePID: {FilePID, "denotes the process id performing file operation", params.PID, []string{"file.pid = 4"}, nil, nil}, + FileKey: {FileKey, "uniquely identifies the file object", params.Uint64, []string{"file.key = 12446738026482168384"}, nil, nil}, + FileInfoClass: {FileInfoClass, "identifies the file information class", params.Enum, []string{"file.info_class = 'Allocation'"}, nil, nil}, + FileInfoAllocationSize: {FileInfoAllocationSize, "file allocation size", params.Uint64, []string{"file.info.allocation_size > 645400"}, nil, nil}, + FileInfoEOFSize: {FileInfoEOFSize, "file EOF size", params.Uint64, []string{"file.info.eof_size > 1000"}, nil, nil}, + FileInfoIsDispositionDeleteFile: {FileInfoIsDispositionDeleteFile, "indicates if the file is deleted when its handle is closed", params.Bool, []string{"file.info.is_disposition_file_delete = true"}, nil, nil}, + RegistryPath: {RegistryPath, "fully qualified registry path", params.UnicodeString, []string{"registry.path = 'HKEY_LOCAL_MACHINE\\SYSTEM'"}, nil, nil}, + RegistryKeyName: {RegistryKeyName, "registry key name", params.UnicodeString, []string{"registry.key.name = 'CurrentControlSet'"}, nil, nil}, + RegistryKCB: {RegistryKCB, "registry KCB address", params.Address, []string{"registry.kcb = 'FFFFB905D60C2268'"}, nil, nil}, + RegistryValue: {RegistryValue, "registry value name", params.UnicodeString, []string{"registry.value = 'Epoch'"}, nil, nil}, + RegistryValueType: {RegistryValueType, "type of registry value", params.UnicodeString, []string{"registry.value.type = 'REG_SZ'"}, nil, nil}, + RegistryData: {RegistryData, "registry value captured data", params.Object, []string{"registry.data = '%SystemRoot%'"}, nil, nil}, + RegistryStatus: {RegistryStatus, "status of registry operation", params.UnicodeString, []string{"registry.status != 'success'"}, nil, nil}, + NetDIP: {NetDIP, "destination IP address", params.IP, []string{"net.dip = 172.17.0.3"}, nil, nil}, + NetSIP: {NetSIP, "source IP address", params.IP, []string{"net.sip = 127.0.0.1"}, nil, nil}, + NetDport: {NetDport, "destination port", params.Uint16, []string{"net.dport in (80, 443, 8080)"}, nil, nil}, + NetSport: {NetSport, "source port", params.Uint16, []string{"net.sport != 3306"}, nil, nil}, + NetDportName: {NetDportName, "destination port name", params.AnsiString, []string{"net.dport.name = 'dns'"}, nil, nil}, + NetSportName: {NetSportName, "source port name", params.AnsiString, []string{"net.sport.name = 'http'"}, nil, nil}, + NetL4Proto: {NetL4Proto, "layer 4 protocol name", params.AnsiString, []string{"net.l4.proto = 'TCP"}, nil, nil}, + NetPacketSize: {NetPacketSize, "packet size", params.Uint32, []string{"net.size > 512"}, nil, nil}, + NetSIPNames: {NetSIPNames, "source IP names", params.Slice, []string{"net.sip.names in ('github.com.')"}, nil, nil}, + NetDIPNames: {NetDIPNames, "destination IP names", params.Slice, []string{"net.dip.names in ('github.com.')"}, nil, nil}, + HandleID: {HandleID, "handle identifier", params.Uint16, []string{"handle.id = 24"}, nil, nil}, + HandleObject: {HandleObject, "handle object address", params.Address, []string{"handle.object = 'FFFFB905DBF61988'"}, nil, nil}, + HandleName: {HandleName, "handle name", params.UnicodeString, []string{"handle.name = '\\Device\\NamedPipe\\chrome.12644.28.105826381'"}, nil, nil}, + HandleType: {HandleType, "handle type", params.AnsiString, []string{"handle.type = 'Mutant'"}, nil, nil}, + PeNumSections: {PeNumSections, "number of sections", params.Uint16, []string{"pe.nsections < 5"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsPeNumSections}}, nil}, + PeNumSymbols: {PeNumSymbols, "number of entries in the symbol table", params.Uint32, []string{"pe.nsymbols > 230"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsPeNumSymbols}}, nil}, + PeBaseAddress: {PeBaseAddress, "image base address", params.Address, []string{"pe.address.base = '140000000'"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsPeBaseAddress}}, nil}, + PeEntrypoint: {PeEntrypoint, "address of the entrypoint function", params.Address, []string{"pe.address.entrypoint = '20110'"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsPeEntrypoint}}, nil}, + PeSymbols: {PeSymbols, "imported symbols", params.Slice, []string{"pe.symbols in ('GetTextFaceW', 'GetProcessHeap')"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsPeSymbols}}, nil}, + PeImports: {PeImports, "imported dynamic linked libraries", params.Slice, []string{"pe.imports in ('msvcrt.dll', 'GDI32.dll'"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsPeImports}}, nil}, + PeResources: {PeResources, "version resources", params.Map, []string{"pe.resources[FileDescription] = 'Notepad'"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsPeResources}}, &Argument{Optional: true, Pattern: "[a-zA-Z0-9_]+", ValidationFunc: func(s string) bool { + for _, c := range s { + switch { + case unicode.IsLower(c): + case unicode.IsUpper(c): + case unicode.IsNumber(c): + case c == '_': + default: + return false + } + } + return true + }}}, + PeCompany: {PeCompany, "internal company name of the file provided at compile-time", params.UnicodeString, []string{"pe.company = 'Microsoft Corporation'"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsPeCompany}}, nil}, + PeCopyright: {PeCopyright, "copyright notice for the file emitted at compile-time", params.UnicodeString, []string{"pe.copyright = '© Microsoft Corporation'"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsPeCopyright}}, nil}, + PeDescription: {PeDescription, "internal description of the file provided at compile-time", params.UnicodeString, []string{"pe.description = 'Notepad'"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsPeDescription}}, nil}, + PeFileName: {PeFileName, "original file name supplied at compile-time", params.UnicodeString, []string{"pe.file.name = 'NOTEPAD.EXE'"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsPeFileName}}, nil}, + PeFileVersion: {PeFileVersion, "file version supplied at compile-time", params.UnicodeString, []string{"pe.file.version = '10.0.18362.693 (WinBuild.160101.0800)'"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsPeFileVersion}}, nil}, + PeProduct: {PeProduct, "internal product name of the file provided at compile-time", params.UnicodeString, []string{"pe.product = 'Microsoft® Windows® Operating System'"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsPeProduct}}, nil}, + PeProductVersion: {PeProductVersion, "internal product version of the file provided at compile-time", params.UnicodeString, []string{"pe.product.version = '10.0.18362.693'"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsPeProductVersion}}, nil}, + PeIsDLL: {PeIsDLL, "indicates if the loaded image or created file is a DLL", params.Bool, []string{"pe.is_dll'"}, &Deprecation{Since: "2.0.0", Fields: []Field{FileIsDLL, ImageIsDLL}}, nil}, + PeIsDriver: {PeIsDriver, "indicates if the loaded image or created file is a driver", params.Bool, []string{"pe.is_driver'"}, &Deprecation{Since: "2.0.0", Fields: []Field{FileIsDriver, ImageIsDriver}}, nil}, + PeIsExecutable: {PeIsExecutable, "indicates if the loaded image or created file is an executable", params.Bool, []string{"pe.is_exec'"}, &Deprecation{Since: "2.0.0", Fields: []Field{FileIsExecutable, ImageIsExecutable}}, nil}, + PeImphash: {PeImphash, "import hash", params.AnsiString, []string{"pe.impash = '5d3861c5c547f8a34e471ba273a732b2'"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsPeImphash}}, nil}, + PeIsDotnet: {PeIsDotnet, "indicates if PE contains CLR data", params.Bool, []string{"pe.is_dotnet"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsPeIsDotnet}}, nil}, + PeAnomalies: {PeAnomalies, "contains PE anomalies detected during parsing", params.Slice, []string{"pe.anomalies in ('number of sections is 0')"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsPeAnomalies}}, nil}, + PeIsSigned: {PeIsSigned, "indicates if the PE has embedded or catalog signature", params.Bool, []string{"pe.is_signed"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsSignatureExists}}, nil}, + PeIsTrusted: {PeIsTrusted, "indicates if the PE certificate chain is trusted", params.Bool, []string{"pe.is_trusted"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsSignatureTrusted}}, nil}, + PeCertSerial: {PeCertSerial, "PE certificate serial number", params.UnicodeString, []string{"pe.cert.serial = '330000023241fb59996dcc4dff000000000232'"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsSignatureSerial}}, nil}, + PeCertSubject: {PeCertSubject, "PE certificate subject", params.UnicodeString, []string{"pe.cert.subject contains 'Washington, Redmond, Microsoft Corporation'"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsSignatureSubject}}, nil}, + PeCertIssuer: {PeCertIssuer, "PE certificate CA", params.UnicodeString, []string{"pe.cert.issuer contains 'Washington, Redmond, Microsoft Corporation'"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsSignatureIssuer}}, nil}, + PeCertAfter: {PeCertAfter, "PE certificate expiration date", params.Time, []string{"pe.cert.after contains '2024-02-01 00:05:42 +0000 UTC'"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsSignatureAfter}}, nil}, + PeCertBefore: {PeCertBefore, "PE certificate enrollment date", params.Time, []string{"pe.cert.before contains '2024-02-01 00:05:42 +0000 UTC'"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsSignatureBefore}}, nil}, + PeIsModified: {PeIsModified, "indicates if disk and in-memory PE headers differ", params.Bool, []string{"pe.is_modified"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsPeIsModified}}, nil}, + MemBaseAddress: {MemBaseAddress, "region base address", params.Address, []string{"mem.address = '211d13f2000'"}, nil, nil}, + MemRegionSize: {MemRegionSize, "region size", params.Uint64, []string{"mem.size > 438272"}, nil, nil}, + MemAllocType: {MemAllocType, "region allocation or release type", params.Flags, []string{"mem.alloc = 'COMMIT'"}, nil, nil}, + MemPageType: {MemPageType, "page type of the allocated region", params.Enum, []string{"mem.type = 'PRIVATE'"}, nil, nil}, + MemProtection: {MemProtection, "allocated region protection type", params.Enum, []string{"mem.protection = 'READWRITE'"}, nil, nil}, + MemProtectionMask: {MemProtectionMask, "allocated region protection in mask notation", params.Enum, []string{"mem.protection.mask = 'RWX'"}, nil, nil}, + DNSName: {DNSName, "dns query name", params.UnicodeString, []string{"dns.name = 'example.org'"}, nil, nil}, + DNSRR: {DNSRR, "dns resource record type", params.AnsiString, []string{"dns.rr = 'AA'"}, nil, nil}, + DNSOptions: {DNSOptions, "dns query options", params.Flags64, []string{"dns.options in ('ADDRCONFIG', 'DUAL_ADDR')"}, nil, nil}, + DNSRcode: {DNSRR, "dns response status", params.AnsiString, []string{"dns.rcode = 'NXDOMAIN'"}, nil, nil}, + DNSAnswers: {DNSAnswers, "dns response answers", params.Slice, []string{"dns.answers in ('o.lencr.edgesuite.net', 'a1887.dscq.akamai.net')"}, nil, nil}, + ThreadpoolPoolID: {ThreadpoolPoolID, "thread pool identifier", params.Address, []string{"threadpool.id = '20f5fc02440'"}, nil, nil}, + ThreadpoolTaskID: {ThreadpoolTaskID, "thread pool task identifier", params.Address, []string{"threadpool.task.id = '20f7ecd21f8'"}, nil, nil}, + ThreadpoolCallbackAddress: {ThreadpoolCallbackAddress, "thread pool callback address", params.Address, []string{"threadpool.callback.address = '7ff868739ed0'"}, nil, nil}, + ThreadpoolCallbackSymbol: {ThreadpoolCallbackSymbol, "thread pool callback symbol", params.UnicodeString, []string{"threadpool.callback.symbol = 'RtlDestroyQueryDebugBuffer'"}, nil, nil}, + ThreadpoolCallbackModule: {ThreadpoolCallbackModule, "thread pool module containing the callback symbol", params.UnicodeString, []string{"threadpool.callback.module contains 'ntdll.dll'"}, nil, nil}, + ThreadpoolCallbackContext: {ThreadpoolCallbackContext, "thread pool callback context address", params.Address, []string{"threadpool.callback.context = '1df41e07bd0'"}, nil, nil}, + ThreadpoolCallbackContextRip: {ThreadpoolCallbackContextRip, "thread pool callback thread context instruction pointer", params.Address, []string{"threadpool.callback.context.rip = '1df42ffc1f8'"}, nil, nil}, + ThreadpoolCallbackContextRipSymbol: {ThreadpoolCallbackContextRipSymbol, "thread pool callback thread context instruction pointer symbol", params.UnicodeString, []string{"threadpool.callback.context.rip.symbol = 'VirtualProtect'"}, nil, nil}, + ThreadpoolCallbackContextRipModule: {ThreadpoolCallbackContextRipModule, "thread pool callback thread context instruction pointer symbol module", params.UnicodeString, []string{"threadpool.callback.context.rip.module contains 'ntdll.dll'"}, nil, nil}, + ThreadpoolSubprocessTag: {ThreadpoolSubprocessTag, "thread pool service identifier", params.Address, []string{"threadpool.subprocess_tag = '10d'"}, nil, nil}, + ThreadpoolTimerDuetime: {ThreadpoolTimerDuetime, "thread pool timer due time", params.Uint64, []string{"threadpool.timer.duetime > 10"}, nil, nil}, + ThreadpoolTimerSubqueue: {ThreadpoolTimerSubqueue, "thread pool timer subqueue address", params.Address, []string{"threadpool.timer.subqueue = '1db401703e8'"}, nil, nil}, + ThreadpoolTimer: {ThreadpoolTimer, "thread pool timer address", params.Address, []string{"threadpool.timer.address = '3e8'"}, nil, nil}, + ThreadpoolTimerPeriod: {ThreadpoolTimerPeriod, "thread pool timer period", params.Uint32, []string{"threadpool.timer.period = 0'"}, nil, nil}, + ThreadpoolTimerWindow: {ThreadpoolTimerWindow, "thread pool timer tolerate period", params.Uint32, []string{"threadpool.timer.window = 0'"}, nil, nil}, + ThreadpoolTimerAbsolute: {ThreadpoolTimerAbsolute, "indicates if the thread pool timer is absolute or relative", params.Bool, []string{"threadpool.timer.is_absolute = true'"}, nil, nil}, +}) diff --git a/pkg/filter/filter_test.go b/pkg/filter/filter_windows_test.go similarity index 99% rename from pkg/filter/filter_test.go rename to pkg/filter/filter_windows_test.go index a7a77e48b..9189a0107 100644 --- a/pkg/filter/filter_test.go +++ b/pkg/filter/filter_windows_test.go @@ -64,7 +64,10 @@ var cfg = &config.Config{ EnableThreadpoolEvents: true, }, Filters: &config.Filters{}, - PE: pe.Config{Enabled: true}, +} + +func init() { + cfg.PE = pe.Config{Enabled: true} } func TestFilterCompile(t *testing.T) { diff --git a/pkg/filter/ql/function.go b/pkg/filter/ql/function.go index 733f4c405..aca97a2e3 100644 --- a/pkg/filter/ql/function.go +++ b/pkg/filter/ql/function.go @@ -21,14 +21,12 @@ package ql import ( "fmt" "maps" - "path/filepath" "regexp" "sort" "strings" "github.com/rabbitstack/fibratus/pkg/callstack" "github.com/rabbitstack/fibratus/pkg/filter/fields" - "github.com/rabbitstack/fibratus/pkg/pe" pstypes "github.com/rabbitstack/fibratus/pkg/ps/types" "github.com/rabbitstack/fibratus/pkg/filter/ql/functions" @@ -68,7 +66,6 @@ var funcs = map[string]FunctionDef{ functions.SubstrFn.String(): &functions.Substr{}, functions.EntropyFn.String(): &functions.Entropy{}, functions.RegexFn.String(): functions.NewRegex(), - functions.IsMinidumpFn.String(): &functions.IsMinidump{}, functions.BaseFn.String(): &functions.Base{}, functions.DirFn.String(): &functions.Dir{}, functions.SymlinkFn.String(): &functions.Symlink{}, @@ -76,7 +73,6 @@ var funcs = map[string]FunctionDef{ functions.GlobFn.String(): &functions.Glob{}, functions.IsAbsFn.String(): &functions.IsAbs{}, functions.VolumeFn.String(): &functions.Volume{}, - functions.GetRegValueFn.String(): &functions.GetRegValue{}, functions.YaraFn.String(): &functions.Yara{}, functions.ForeachFn.String(): &Foreach{}, functions.CountFn.String(): &functions.Count{}, @@ -219,35 +215,19 @@ func (f *Foreach) Call(args []interface{}) (interface{}, bool) { return true, true } } - case []pstypes.Module: - for _, mod := range elems { - if f.evalExpr(e, useCallValuer, f.moduleMapValuer(segments, mod), valuer) { - return true, true - } - } - case map[uint32]pstypes.Thread: - for _, thread := range elems { - if f.evalExpr(e, useCallValuer, f.threadMapValuer(segments, thread), valuer) { - return true, true - } - } case []pstypes.Mmap: for _, mmap := range elems { if f.evalExpr(e, useCallValuer, f.mmapMapValuer(segments, mmap), valuer) { return true, true } } - case []pe.Sec: - for _, sec := range elems { - if f.evalExpr(e, useCallValuer, f.sectionMapValuer(segments, sec), valuer) { - return true, true - } - } case callstack.Callstack: if ok, matched := f.foreachCallstack(elems, segments, e, useCallValuer, valuer); ok { return matched, true } return false, false + default: + return f.foreachPlatform(elems, segments, e, useCallValuer, valuer) } return false, false @@ -412,27 +392,6 @@ func (f *Foreach) stringMapValuer(v *BareBoundVariableLiteral, s string) MapValu return MapValuer{v.Value: s} } -// moduleMapValuer returns the map valuer with process module attributes. -func (f *Foreach) moduleMapValuer(segments []*BoundSegmentLiteral, mod pstypes.Module) MapValuer { - var valuer = MapValuer{} - for _, seg := range segments { - key := seg.Value - switch seg.Segment { - case fields.PathSegment: - valuer[key] = mod.Name - case fields.NameSegment: - valuer[key] = filepath.Base(mod.Name) - case fields.AddressSegment: - valuer[key] = mod.BaseAddress.String() - case fields.SizeSegment: - valuer[key] = mod.Size - case fields.ChecksumSegment: - valuer[key] = mod.Checksum - } - } - return valuer -} - // procMapValuer returns the map valuer with process attributes. func (f *Foreach) procMapValuer(segments []*BoundSegmentLiteral, proc *pstypes.PS) MapValuer { var valuer = MapValuer{} @@ -451,45 +410,11 @@ func (f *Foreach) procMapValuer(segments []*BoundSegmentLiteral, proc *pstypes.P valuer[key] = proc.Args case fields.CwdSegment: valuer[key] = proc.Cwd - case fields.SIDSegment: - valuer[key] = proc.SID - case fields.SessionIDSegment: - valuer[key] = proc.SessionID case fields.UsernameSegment: valuer[key] = proc.Username - case fields.DomainSegment: - valuer[key] = proc.Domain - case fields.TokenIntegrityLevelSegment: - valuer[key] = proc.TokenIntegrityLevel - case fields.TokenIsElevatedSegment: - valuer[key] = proc.IsTokenElevated - case fields.TokenElevationTypeSegment: - valuer[key] = proc.TokenElevationType - } - } - return valuer -} - -// threadMapValuer returns the map valuer with thread information. -func (f *Foreach) threadMapValuer(segments []*BoundSegmentLiteral, thread pstypes.Thread) MapValuer { - var valuer = MapValuer{} - for _, seg := range segments { - key := seg.Value - switch seg.Segment { - case fields.TidSegment: - valuer[key] = thread.Tid - case fields.StartAddressSegment: - valuer[key] = thread.StartAddress.String() - case fields.UserStackBaseSegment: - valuer[key] = thread.UstackBase.String() - case fields.UserStackLimitSegment: - valuer[key] = thread.UstackLimit.String() - case fields.KernelStackBaseSegment: - valuer[key] = thread.KstackBase.String() - case fields.KernelStackLimitSegment: - valuer[key] = thread.KstackLimit.String() } } + addPlatformProcessValues(segments, proc, valuer) return valuer } @@ -513,22 +438,3 @@ func (f *Foreach) mmapMapValuer(segments []*BoundSegmentLiteral, mmap pstypes.Mm } return valuer } - -// sectionMapValuer returns map valuer with PE section data. -func (f *Foreach) sectionMapValuer(segments []*BoundSegmentLiteral, section pe.Sec) MapValuer { - var valuer = MapValuer{} - for _, seg := range segments { - key := seg.Value - switch seg.Segment { - case fields.NameSegment: - valuer[key] = section.Name - case fields.SizeSegment: - valuer[key] = section.Size - case fields.EntropySegment: - valuer[key] = section.Entropy - case fields.MD5Segment: - valuer[key] = section.Md5 - } - } - return valuer -} diff --git a/pkg/filter/ql/function_callstack_linux.go b/pkg/filter/ql/function_linux.go similarity index 62% rename from pkg/filter/ql/function_callstack_linux.go rename to pkg/filter/ql/function_linux.go index 3f0754c58..771982b79 100644 --- a/pkg/filter/ql/function_callstack_linux.go +++ b/pkg/filter/ql/function_linux.go @@ -25,8 +25,38 @@ import ( "github.com/rabbitstack/fibratus/pkg/callstack" "github.com/rabbitstack/fibratus/pkg/filter/fields" + pstypes "github.com/rabbitstack/fibratus/pkg/ps/types" ) +func (f *Foreach) foreachPlatform(elems interface{}, segments []*BoundSegmentLiteral, e interface{}, useCallValuer bool, valuer MapValuer) (bool, bool) { + threads, ok := elems.(map[uint64]pstypes.Thread) + if !ok { + return false, false + } + for _, thread := range threads { + if f.evalExpr(e, useCallValuer, f.threadMapValuer(segments, thread), valuer) { + return true, true + } + } + return false, false +} + +func addPlatformProcessValues(_ []*BoundSegmentLiteral, _ *pstypes.PS, _ MapValuer) {} + +// threadMapValuer returns the map valuer with Linux thread information. +func (f *Foreach) threadMapValuer(segments []*BoundSegmentLiteral, thread pstypes.Thread) MapValuer { + valuer := MapValuer{} + for _, seg := range segments { + switch seg.Segment { + case fields.TidSegment: + valuer[seg.Value] = thread.Tid + case fields.PIDSegment: + valuer[seg.Value] = thread.Pid + } + } + return valuer +} + func (f *Foreach) foreachCallstack(elems callstack.Callstack, segments []*BoundSegmentLiteral, e interface{}, useCallValuer bool, valuer MapValuer) (bool, bool) { for _, frame := range elems { if f.evalExpr(e, useCallValuer, f.callstackMapValuer(segments, frame), valuer) { diff --git a/pkg/filter/ql/function_callstack_windows.go b/pkg/filter/ql/function_windows.go similarity index 51% rename from pkg/filter/ql/function_callstack_windows.go rename to pkg/filter/ql/function_windows.go index d8434036e..b8a527756 100644 --- a/pkg/filter/ql/function_callstack_windows.go +++ b/pkg/filter/ql/function_windows.go @@ -22,12 +22,125 @@ package ql import ( + "path/filepath" + "github.com/rabbitstack/fibratus/pkg/callstack" "github.com/rabbitstack/fibratus/pkg/filter/fields" + "github.com/rabbitstack/fibratus/pkg/filter/ql/functions" + "github.com/rabbitstack/fibratus/pkg/pe" + pstypes "github.com/rabbitstack/fibratus/pkg/ps/types" "github.com/rabbitstack/fibratus/pkg/util/signature" "golang.org/x/sys/windows" ) +func init() { + funcs[functions.IsMinidumpFn.String()] = &functions.IsMinidump{} + funcs[functions.GetRegValueFn.String()] = &functions.GetRegValue{} +} + +func (f *Foreach) foreachPlatform(elems interface{}, segments []*BoundSegmentLiteral, e interface{}, useCallValuer bool, valuer MapValuer) (bool, bool) { + switch elems := elems.(type) { + case []pstypes.Module: + for _, mod := range elems { + if f.evalExpr(e, useCallValuer, f.moduleMapValuer(segments, mod), valuer) { + return true, true + } + } + case map[uint32]pstypes.Thread: + for _, thread := range elems { + if f.evalExpr(e, useCallValuer, f.threadMapValuer(segments, thread), valuer) { + return true, true + } + } + case []pe.Sec: + for _, sec := range elems { + if f.evalExpr(e, useCallValuer, f.sectionMapValuer(segments, sec), valuer) { + return true, true + } + } + } + return false, false +} + +func addPlatformProcessValues(segments []*BoundSegmentLiteral, proc *pstypes.PS, valuer MapValuer) { + for _, seg := range segments { + switch seg.Segment { + case fields.SIDSegment: + valuer[seg.Value] = proc.SID + case fields.SessionIDSegment: + valuer[seg.Value] = proc.SessionID + case fields.DomainSegment: + valuer[seg.Value] = proc.Domain + case fields.TokenIntegrityLevelSegment: + valuer[seg.Value] = proc.TokenIntegrityLevel + case fields.TokenIsElevatedSegment: + valuer[seg.Value] = proc.IsTokenElevated + case fields.TokenElevationTypeSegment: + valuer[seg.Value] = proc.TokenElevationType + } + } +} + +// moduleMapValuer returns the map valuer with process module attributes. +func (f *Foreach) moduleMapValuer(segments []*BoundSegmentLiteral, mod pstypes.Module) MapValuer { + valuer := MapValuer{} + for _, seg := range segments { + switch seg.Segment { + case fields.PathSegment: + valuer[seg.Value] = mod.Name + case fields.NameSegment: + valuer[seg.Value] = filepath.Base(mod.Name) + case fields.AddressSegment: + valuer[seg.Value] = mod.BaseAddress.String() + case fields.SizeSegment: + valuer[seg.Value] = mod.Size + case fields.ChecksumSegment: + valuer[seg.Value] = mod.Checksum + } + } + return valuer +} + +// threadMapValuer returns the map valuer with thread information. +func (f *Foreach) threadMapValuer(segments []*BoundSegmentLiteral, thread pstypes.Thread) MapValuer { + valuer := MapValuer{} + for _, seg := range segments { + switch seg.Segment { + case fields.TidSegment: + valuer[seg.Value] = thread.Tid + case fields.StartAddressSegment: + valuer[seg.Value] = thread.StartAddress.String() + case fields.UserStackBaseSegment: + valuer[seg.Value] = thread.UstackBase.String() + case fields.UserStackLimitSegment: + valuer[seg.Value] = thread.UstackLimit.String() + case fields.KernelStackBaseSegment: + valuer[seg.Value] = thread.KstackBase.String() + case fields.KernelStackLimitSegment: + valuer[seg.Value] = thread.KstackLimit.String() + } + } + return valuer +} + +// sectionMapValuer returns map valuer with PE section data. +func (f *Foreach) sectionMapValuer(segments []*BoundSegmentLiteral, section pe.Sec) MapValuer { + valuer := MapValuer{} + for _, seg := range segments { + switch seg.Segment { + case fields.NameSegment: + valuer[seg.Value] = section.Name + case fields.SizeSegment: + valuer[seg.Value] = section.Size + case fields.EntropySegment: + valuer[seg.Value] = section.Entropy + case fields.MD5Segment: + valuer[seg.Value] = section.Md5 + } + } + return valuer +} + // foreachCallstack evaluates the predicate against callstack frames. // The first return value indicates whether callstack handling applied; // the second is the match result. diff --git a/pkg/filter/ql/function_test.go b/pkg/filter/ql/function_windows_test.go similarity index 100% rename from pkg/filter/ql/function_test.go rename to pkg/filter/ql/function_windows_test.go diff --git a/pkg/filter/ql/functions/base_test.go b/pkg/filter/ql/functions/base_windows_test.go similarity index 100% rename from pkg/filter/ql/functions/base_test.go rename to pkg/filter/ql/functions/base_windows_test.go diff --git a/pkg/filter/ql/functions/dir_test.go b/pkg/filter/ql/functions/dir_windows_test.go similarity index 100% rename from pkg/filter/ql/functions/dir_test.go rename to pkg/filter/ql/functions/dir_windows_test.go diff --git a/pkg/filter/ql/functions/glob_test.go b/pkg/filter/ql/functions/glob_windows_test.go similarity index 100% rename from pkg/filter/ql/functions/glob_test.go rename to pkg/filter/ql/functions/glob_windows_test.go diff --git a/pkg/filter/ql/functions/is_abs_test.go b/pkg/filter/ql/functions/is_abs_windows_test.go similarity index 100% rename from pkg/filter/ql/functions/is_abs_test.go rename to pkg/filter/ql/functions/is_abs_windows_test.go diff --git a/pkg/filter/ql/functions/volume_test.go b/pkg/filter/ql/functions/volume_windows_test.go similarity index 100% rename from pkg/filter/ql/functions/volume_test.go rename to pkg/filter/ql/functions/volume_windows_test.go diff --git a/pkg/filter/ql/literal_test.go b/pkg/filter/ql/literal_windows_test.go similarity index 100% rename from pkg/filter/ql/literal_test.go rename to pkg/filter/ql/literal_windows_test.go diff --git a/pkg/filter/ql/parser_test.go b/pkg/filter/ql/parser_windows_test.go similarity index 100% rename from pkg/filter/ql/parser_test.go rename to pkg/filter/ql/parser_windows_test.go diff --git a/pkg/filter/util.go b/pkg/filter/util.go index 700b07d07..dce09e5b7 100644 --- a/pkg/filter/util.go +++ b/pkg/filter/util.go @@ -23,18 +23,9 @@ import ( "net" "strings" - "github.com/rabbitstack/fibratus/pkg/event" "github.com/rabbitstack/fibratus/pkg/util/bytes" ) -// framePID returns the pid associated with the stack frame. -func framePID(e *event.Event) event.PID { - if !e.Callstack.IsEmpty() && e.Callstack.FrameAt(0).PID != 0 { - return event.PID(e.Callstack.FrameAt(0).PID) - } - return e.PID -} - // CompareSeqLink returns true if any value // in the sequence link slice equals to the // given LHS value. diff --git a/pkg/filter/ql/functions/get_reg_value_linux.go b/pkg/filter/util_linux.go similarity index 72% rename from pkg/filter/ql/functions/get_reg_value_linux.go rename to pkg/filter/util_linux.go index 6295a79cd..752ccdb36 100644 --- a/pkg/filter/ql/functions/get_reg_value_linux.go +++ b/pkg/filter/util_linux.go @@ -18,12 +18,11 @@ * limitations under the License. */ -package functions +package filter -type GetRegValue struct{} +import "github.com/rabbitstack/fibratus/pkg/event" -func (GetRegValue) Call([]interface{}) (interface{}, bool) { return nil, false } -func (GetRegValue) Desc() FunctionDesc { - return FunctionDesc{Name: GetRegValueFn} +// framePID returns the process identifier associated with the event. +func framePID(e *event.Event) event.PID { + return e.PID } -func (GetRegValue) Name() Fn { return GetRegValueFn } diff --git a/pkg/filter/accessor_narrow_linux.go b/pkg/filter/util_windows.go similarity index 60% rename from pkg/filter/accessor_narrow_linux.go rename to pkg/filter/util_windows.go index 1e9105ca0..2983997c5 100644 --- a/pkg/filter/accessor_narrow_linux.go +++ b/pkg/filter/util_windows.go @@ -1,6 +1,7 @@ -//go:build linux +//go:build windows /* + * Copyright 2021-present by Nedim Sabic Sabic * Copyright 2026 by Mostafa Moradian * https://www.fibratus.io * All Rights Reserved. @@ -20,23 +21,12 @@ package filter -func (f *filter) pruneUnusedAccessors() { - removeEvtAccessor := true - removePsAccessor := true +import "github.com/rabbitstack/fibratus/pkg/event" - for _, field := range f.fields { - switch { - case field.Name.IsEvtField() || field.Name.IsKevtField(): - removeEvtAccessor = false - case field.Name.IsPsField(): - removePsAccessor = false - } - } - - if removeEvtAccessor { - f.removeAccessor(&evtAccessor{}) - } - if removePsAccessor { - f.removeAccessor(&psAccessor{}) +// framePID returns the process identifier associated with the stack frame. +func framePID(e *event.Event) event.PID { + if !e.Callstack.IsEmpty() && e.Callstack.FrameAt(0).PID != 0 { + return event.PID(e.Callstack.FrameAt(0).PID) } + return e.PID } diff --git a/pkg/rules/action/kill_linux.go b/pkg/rules/action/kill_linux.go index 04ff289f8..1cc0bbbb0 100644 --- a/pkg/rules/action/kill_linux.go +++ b/pkg/rules/action/kill_linux.go @@ -20,10 +20,14 @@ package action -import "fmt" +import ( + "fmt" + + "github.com/rabbitstack/fibratus/pkg/event" +) // Kill terminates all processes with specified pids. // The signal-based Linux implementation lands with the detection work. -func Kill(pids []uint32) error { +func Kill(pids []event.PID) error { return fmt.Errorf("kill action is not implemented on Linux yet (pids=%v)", pids) } diff --git a/pkg/rules/action/kill_windows.go b/pkg/rules/action/kill_windows.go index 926414441..1b2bf830a 100644 --- a/pkg/rules/action/kill_windows.go +++ b/pkg/rules/action/kill_windows.go @@ -20,14 +20,16 @@ package action import ( "fmt" - "github.com/rabbitstack/fibratus/pkg/util/multierror" - "golang.org/x/sys/windows" "os" "syscall" + + "github.com/rabbitstack/fibratus/pkg/event" + "github.com/rabbitstack/fibratus/pkg/util/multierror" + "golang.org/x/sys/windows" ) // Kill terminates all processes with specified pids. -func Kill(pids []uint32) error { +func Kill(pids []event.PID) error { errs := make([]error, 0) for _, pid := range pids { err := terminate(pid) diff --git a/pkg/rules/compiler.go b/pkg/rules/compiler.go index d0c107df3..668e13078 100644 --- a/pkg/rules/compiler.go +++ b/pkg/rules/compiler.go @@ -220,33 +220,6 @@ func (c *compiler) visitApproverPredicates(node ql.Node) { ql.WalkFunc(node, walk) } -// referencesTargetEvents checks whether the rule AST contains -// an event type filter for high-volume events we want to approve. -func (c *compiler) referencesApproverEvents(root ql.Node) bool { - var found bool - ql.WalkFunc(root, func(n ql.Node) { - expr, ok := n.(*ql.BinaryExpr) - if !ok { - return - } - - // direct event match. We also include SetFileInformation - // to approve any paths referenced in the condition - if c.containsEventTypes(expr, event.RegOpenKey, event.OpenThread, event.OpenProcess, event.SetFileInformation) { - found = true - return - } - - // for file events require open file operation - if expr.Op == ql.And { - if c.containsEventTypes(expr, event.CreateFile) && c.containsFieldMatch(expr, fields.FileOperation, ql.Eq, "OPEN") { - found = true - } - } - }) - return found -} - func (c *compiler) containsEventTypes(root ql.Node, types ...event.Type) bool { var contains bool ql.WalkFunc(root, func(n ql.Node) { @@ -362,13 +335,7 @@ func (c *compiler) buildCompileResult(filters map[*config.FilterConfig]filter.Fi if typ.Subcategory() == event.DNS { rs.HasDNSEvents = true } - if typ == event.MapViewFile || typ == event.UnmapViewFile { - rs.HasVAMapEvents = true - } - if typ == event.OpenProcess || typ == event.OpenThread || typ == event.SetThreadContext || - typ == event.CreateSymbolicLinkObject { - rs.HasAuditAPIEvents = true - } + updatePlatformCompileResult(rs, typ) if m[typ] { continue diff --git a/pkg/filter/ql/functions/minidump_linux.go b/pkg/rules/compiler_linux.go similarity index 56% rename from pkg/filter/ql/functions/minidump_linux.go rename to pkg/rules/compiler_linux.go index 98e57df6b..e6dbf4d9a 100644 --- a/pkg/filter/ql/functions/minidump_linux.go +++ b/pkg/rules/compiler_linux.go @@ -18,22 +18,16 @@ * limitations under the License. */ -package functions +package rules -// IsMinidump determines if the specified file contains the minidump signature. -type IsMinidump struct{} +import ( + "github.com/rabbitstack/fibratus/pkg/config" + "github.com/rabbitstack/fibratus/pkg/event" + "github.com/rabbitstack/fibratus/pkg/filter/ql" +) -func (f IsMinidump) Call(args []interface{}) (interface{}, bool) { - return false, len(args) >= 1 +func (*compiler) referencesApproverEvents(ql.Node) bool { + return false } -func (f IsMinidump) Desc() FunctionDesc { - return FunctionDesc{ - Name: IsMinidumpFn, - Args: []FunctionArgDesc{ - {Keyword: "file", Types: []ArgType{Field, BoundField, BoundSegment, BareBoundVariable, Func, String}, Required: true}, - }, - } -} - -func (f IsMinidump) Name() Fn { return IsMinidumpFn } +func updatePlatformCompileResult(*config.RulesCompileResult, event.Type) {} diff --git a/pkg/rules/compiler_linux_test.go b/pkg/rules/compiler_linux_test.go new file mode 100644 index 000000000..5ab4c325b --- /dev/null +++ b/pkg/rules/compiler_linux_test.go @@ -0,0 +1,52 @@ +//go:build linux + +/* + * Copyright 2026 by Mostafa Moradian + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package rules + +import ( + "os" + "path/filepath" + "testing" + + "github.com/rabbitstack/fibratus/pkg/config" + "github.com/rabbitstack/fibratus/pkg/ps" + "github.com/stretchr/testify/require" +) + +func TestCompilerLinuxRule(t *testing.T) { + rule := filepath.Join(t.TempDir(), "execve.yml") + require.NoError(t, os.WriteFile(rule, []byte(`name: Linux process execution +id: 4d17dc44-cc9f-4f13-9a31-23c6529ff46e +version: 1.0.0 +min-engine-version: 3.0.0 +condition: evt.name = 'execve' and ps.name = 'bash' +`), 0o600)) + + cfg := &config.Config{ + Filters: &config.Filters{ + Rules: config.Rules{FromPaths: []string{rule}}, + }, + } + filters, result, err := newCompiler(ps.NewSnapshotter(), cfg).compile() + require.NoError(t, err) + require.Len(t, filters, 1) + require.NotNil(t, result) + require.True(t, result.HasProcEvents) +} diff --git a/pkg/rules/compiler_windows.go b/pkg/rules/compiler_windows.go new file mode 100644 index 000000000..8b8320cc2 --- /dev/null +++ b/pkg/rules/compiler_windows.go @@ -0,0 +1,63 @@ +//go:build windows + +/* + * Copyright 2021-present by Nedim Sabic Sabic + * Copyright 2026 by Mostafa Moradian + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package rules + +import ( + "github.com/rabbitstack/fibratus/pkg/config" + "github.com/rabbitstack/fibratus/pkg/event" + "github.com/rabbitstack/fibratus/pkg/filter/fields" + "github.com/rabbitstack/fibratus/pkg/filter/ql" +) + +// referencesApproverEvents checks whether the rule AST contains an event type +// filter for high-volume Windows events that can be approved by the source. +func (c *compiler) referencesApproverEvents(root ql.Node) bool { + var found bool + ql.WalkFunc(root, func(n ql.Node) { + expr, ok := n.(*ql.BinaryExpr) + if !ok { + return + } + + if c.containsEventTypes(expr, event.RegOpenKey, event.OpenThread, event.OpenProcess, event.SetFileInformation) { + found = true + return + } + + if expr.Op == ql.And && + c.containsEventTypes(expr, event.CreateFile) && + c.containsFieldMatch(expr, fields.FileOperation, ql.Eq, "OPEN") { + found = true + } + }) + return found +} + +func updatePlatformCompileResult(rs *config.RulesCompileResult, typ event.Type) { + if typ == event.MapViewFile || typ == event.UnmapViewFile { + rs.HasVAMapEvents = true + } + if typ == event.OpenProcess || typ == event.OpenThread || typ == event.SetThreadContext || + typ == event.CreateSymbolicLinkObject { + rs.HasAuditAPIEvents = true + } +} diff --git a/pkg/rules/compiler_test.go b/pkg/rules/compiler_windows_test.go similarity index 100% rename from pkg/rules/compiler_test.go rename to pkg/rules/compiler_windows_test.go diff --git a/pkg/rules/engine_test.go b/pkg/rules/engine_windows_test.go similarity index 100% rename from pkg/rules/engine_test.go rename to pkg/rules/engine_windows_test.go diff --git a/pkg/rules/sequence.go b/pkg/rules/sequence.go index d6cc20a90..58d335696 100644 --- a/pkg/rules/sequence.go +++ b/pkg/rules/sequence.go @@ -567,10 +567,10 @@ func (s *sequenceState) expire(e *event.Event) bool { // to the final sequence slot, it is safe to expire // the whole sequence pid := event.PID(rhs.Params.MustGetPid()) - if lhs.Type == event.CreateProcess && isFinalSlot { + if lhs.IsCreateProcess() && isFinalSlot { return event.PID(lhs.Params.MustGetPid()) == pid } - if lhs.Type == event.CreateThread { + if lhs.IsCreateThread() { // if the pids differ, the thread // is created in a remote process. // Sequence can be expired only if diff --git a/pkg/rules/sequence_test.go b/pkg/rules/sequence_windows_test.go similarity index 100% rename from pkg/rules/sequence_test.go rename to pkg/rules/sequence_windows_test.go From 8a87aceb0b655442b04d6a9116cb3c0f82c72b6b Mon Sep 17 00:00:00 2001 From: Mostafa Moradian Date: Mon, 10 Aug 2026 23:36:45 +0200 Subject: [PATCH 26/28] refactor(ps): remove Windows concepts from Linux process state Model Linux process/thread state with 64-bit identifiers and Linux-native resources, expose stable process UUIDs, and remove redundant snapshot operations. Split alert serialization and utility implementations by platform, dropping Linux PE, registry, and NTSTATUS stubs. --- pkg/alertsender/alert.go | 170 +++--------------- pkg/alertsender/alert_process_linux.go | 68 +++++++ pkg/alertsender/alert_process_windows.go | 88 +++++++++ pkg/pe/types_linux.go | 36 ---- pkg/ps/process_key.go | 25 --- pkg/ps/snapshotter_linux.go | 13 +- pkg/ps/types/types_linux.go | 134 ++++++++------ .../types/types_linux_test.go} | 16 +- .../{colorizer_stub.go => colorizer_linux.go} | 2 +- pkg/util/log/{logger.go => logger_windows.go} | 9 +- ...{logger_test.go => logger_windows_test.go} | 5 +- pkg/util/ntstatus/status_linux.go | 35 ---- 12 files changed, 282 insertions(+), 319 deletions(-) create mode 100644 pkg/alertsender/alert_process_linux.go create mode 100644 pkg/alertsender/alert_process_windows.go delete mode 100644 pkg/pe/types_linux.go delete mode 100644 pkg/ps/process_key.go rename pkg/{util/key/key_linux.go => ps/types/types_linux_test.go} (68%) rename pkg/util/colorizer/{colorizer_stub.go => colorizer_linux.go} (97%) rename pkg/util/log/{logger.go => logger_windows.go} (99%) rename pkg/util/log/{logger_test.go => logger_windows_test.go} (99%) delete mode 100644 pkg/util/ntstatus/status_linux.go diff --git a/pkg/alertsender/alert.go b/pkg/alertsender/alert.go index 988d25f30..7e355857f 100644 --- a/pkg/alertsender/alert.go +++ b/pkg/alertsender/alert.go @@ -166,115 +166,47 @@ func (a *Alert) MDToHTML() error { return nil } +type alertJSON struct { + ID string `json:"id"` + Title string `json:"title"` + Severity string `json:"severity"` + Text string `json:"text,omitempty"` + Description string `json:"description"` + Labels map[string]string `json:"labels,omitempty"` + Events []alertJSONEvent `json:"events"` +} + +type alertJSONEvent struct { + Name string `json:"name"` + Category string `json:"category"` + Timestamp time.Time `json:"timestamp"` + Params map[string]any `json:"params"` + Callstack []string `json:"callstack,omitempty"` + Proc *alertProcess `json:"proc,omitempty"` +} + // MarshalJSON encodes the alert to JSON format. func (a Alert) MarshalJSON() ([]byte, error) { - var msg = &struct { - ID string `json:"id"` - Title string `json:"title"` - Severity string `json:"severity"` - Text string `json:"text,omitempty"` - Description string `json:"description"` - Labels map[string]string `json:"labels,omitempty"` - Events []struct { - Name string `json:"name"` - Category string `json:"category"` - Timestamp time.Time `json:"timestamp"` - Params map[string]any `json:"params"` - Callstack []string `json:"callstack,omitempty"` - Proc *struct { - PID event.PID `json:"pid"` - TID uint32 `json:"tid"` - PPID event.PID `json:"ppid"` - Name string `json:"name"` - Exe string `json:"exe"` - Cmdline string `json:"cmdline,omitempty"` - Pname string `json:"parent_name,omitempty"` - Pcmdline string `json:"parent_cmdline,omitempty"` - Cwd string `json:"cwd,omitempty"` - SID string `json:"sid"` - Username string `json:"username"` - Domain string `json:"domain"` - SessionID uint32 `json:"session_id"` - IntegrityLevel string `json:"integrity_level"` - IsWOW64 bool `json:"is_wow64"` - IsPackaged bool `json:"is_packaged"` - IsProtected bool `json:"is_protected"` - Ancestors []string `json:"ancestors"` - } `json:"proc,omitempty"` - } `json:"events"` - }{ + msg := alertJSON{ ID: a.ID, Title: a.Title, Severity: a.Severity.String(), Text: a.Text, Description: a.Description, Labels: a.Labels, + Events: make([]alertJSONEvent, 0, len(a.Events)), } - events := make([]struct { - Name string `json:"name"` - Category string `json:"category"` - Timestamp time.Time `json:"timestamp"` - Params map[string]any `json:"params"` - Callstack []string `json:"callstack,omitempty"` - Proc *struct { - PID event.PID `json:"pid"` - TID uint32 `json:"tid"` - PPID event.PID `json:"ppid"` - Name string `json:"name"` - Exe string `json:"exe"` - Cmdline string `json:"cmdline,omitempty"` - Pname string `json:"parent_name,omitempty"` - Pcmdline string `json:"parent_cmdline,omitempty"` - Cwd string `json:"cwd,omitempty"` - SID string `json:"sid"` - Username string `json:"username"` - Domain string `json:"domain"` - SessionID uint32 `json:"session_id"` - IntegrityLevel string `json:"integrity_level"` - IsWOW64 bool `json:"is_wow64"` - IsPackaged bool `json:"is_packaged"` - IsProtected bool `json:"is_protected"` - Ancestors []string `json:"ancestors"` - } `json:"proc,omitempty"` - }, 0, len(a.Events)) - for _, e := range a.Events { - var evt = struct { - Name string `json:"name"` - Category string `json:"category"` - Timestamp time.Time `json:"timestamp"` - Params map[string]any `json:"params"` - Callstack []string `json:"callstack,omitempty"` - Proc *struct { - PID event.PID `json:"pid"` - TID uint32 `json:"tid"` - PPID event.PID `json:"ppid"` - Name string `json:"name"` - Exe string `json:"exe"` - Cmdline string `json:"cmdline,omitempty"` - Pname string `json:"parent_name,omitempty"` - Pcmdline string `json:"parent_cmdline,omitempty"` - Cwd string `json:"cwd,omitempty"` - SID string `json:"sid"` - Username string `json:"username"` - Domain string `json:"domain"` - SessionID uint32 `json:"session_id"` - IntegrityLevel string `json:"integrity_level"` - IsWOW64 bool `json:"is_wow64"` - IsPackaged bool `json:"is_packaged"` - IsProtected bool `json:"is_protected"` - Ancestors []string `json:"ancestors"` - } `json:"proc,omitempty"` - }{ + evt := alertJSONEvent{ Name: e.Name, Category: string(e.Category), Timestamp: e.Timestamp, Params: make(map[string]any), - Callstack: make([]string, 0, len(e.Callstack)), + Callstack: alertCallstack(e), + Proc: newAlertProcess(e), } - // populate event parameters for _, param := range e.Params { if param.Type == params.Bool || param.Type == params.PID || param.Type == params.TID || param.Type == params.Port || param.IsNumber() { @@ -284,60 +216,8 @@ func (a Alert) MarshalJSON() ([]byte, error) { } } - // populate callstack - for i := range e.Callstack { - frame := e.Callstack[len(e.Callstack)-i-1] - evt.Callstack = append(evt.Callstack, fmt.Sprintf("%v %s!%s", frame.Addr, frame.Module, frame.Symbol)) - } - - ps := e.PS - if ps != nil { - evt.Proc = &struct { - PID event.PID `json:"pid"` - TID uint32 `json:"tid"` - PPID event.PID `json:"ppid"` - Name string `json:"name"` - Exe string `json:"exe"` - Cmdline string `json:"cmdline,omitempty"` - Pname string `json:"parent_name,omitempty"` - Pcmdline string `json:"parent_cmdline,omitempty"` - Cwd string `json:"cwd,omitempty"` - SID string `json:"sid"` - Username string `json:"username"` - Domain string `json:"domain"` - SessionID uint32 `json:"session_id"` - IntegrityLevel string `json:"integrity_level"` - IsWOW64 bool `json:"is_wow64"` - IsPackaged bool `json:"is_packaged"` - IsProtected bool `json:"is_protected"` - Ancestors []string `json:"ancestors"` - }{ - PID: ps.PID, - TID: e.Tid, - PPID: ps.Ppid, - Name: ps.Name, - Exe: ps.Exe, - Cmdline: ps.Cmdline, - Cwd: ps.Cwd, - SID: ps.SID, - Username: ps.Username, - Domain: ps.Domain, - SessionID: ps.SessionID, - IntegrityLevel: ps.TokenIntegrityLevel, - IsWOW64: ps.IsWOW64, - IsPackaged: ps.IsPackaged, - IsProtected: ps.IsProtected, - Ancestors: ps.Ancestors(), - } - if ps.Parent != nil { - evt.Proc.Pname = ps.Parent.Name - evt.Proc.Pcmdline = ps.Parent.Cmdline - } - } - - events = append(events, evt) + msg.Events = append(msg.Events, evt) } - msg.Events = events return json.Marshal(msg) } diff --git a/pkg/alertsender/alert_process_linux.go b/pkg/alertsender/alert_process_linux.go new file mode 100644 index 000000000..4f3703c11 --- /dev/null +++ b/pkg/alertsender/alert_process_linux.go @@ -0,0 +1,68 @@ +//go:build linux + +/* + * Copyright 2026 by Mostafa Moradian + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package alertsender + +import "github.com/rabbitstack/fibratus/pkg/event" + +type alertProcess struct { + PID event.PID `json:"pid"` + TID event.TID `json:"tid"` + PPID event.PID `json:"ppid"` + Name string `json:"name"` + Exe string `json:"exe"` + Cmdline string `json:"cmdline,omitempty"` + Pname string `json:"parent_name,omitempty"` + Pcmdline string `json:"parent_cmdline,omitempty"` + Cwd string `json:"cwd,omitempty"` + UID uint32 `json:"uid"` + GID uint32 `json:"gid"` + Username string `json:"username"` + Ancestors []string `json:"ancestors"` +} + +func newAlertProcess(e *event.Event) *alertProcess { + if e.PS == nil { + return nil + } + proc := &alertProcess{ + PID: e.PS.PID, + TID: e.Tid, + PPID: e.PS.Ppid, + Name: e.PS.Name, + Exe: e.PS.Exe, + Cmdline: e.PS.Cmdline, + Cwd: e.PS.Cwd, + UID: e.PS.UID, + GID: e.PS.GID, + Username: e.PS.Username, + Ancestors: make([]string, 0), + } + proc.Ancestors = append(proc.Ancestors, e.PS.Ancestors()...) + if e.PS.Parent != nil { + proc.Pname = e.PS.Parent.Name + proc.Pcmdline = e.PS.Parent.Cmdline + } + return proc +} + +func alertCallstack(*event.Event) []string { + return nil +} diff --git a/pkg/alertsender/alert_process_windows.go b/pkg/alertsender/alert_process_windows.go new file mode 100644 index 000000000..c92870749 --- /dev/null +++ b/pkg/alertsender/alert_process_windows.go @@ -0,0 +1,88 @@ +//go:build windows + +/* + * Copyright 2021-2022 by Nedim Sabic Sabic + * Copyright 2026 by Mostafa Moradian + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package alertsender + +import ( + "fmt" + + "github.com/rabbitstack/fibratus/pkg/event" +) + +type alertProcess struct { + PID event.PID `json:"pid"` + TID event.TID `json:"tid"` + PPID event.PID `json:"ppid"` + Name string `json:"name"` + Exe string `json:"exe"` + Cmdline string `json:"cmdline,omitempty"` + Pname string `json:"parent_name,omitempty"` + Pcmdline string `json:"parent_cmdline,omitempty"` + Cwd string `json:"cwd,omitempty"` + SID string `json:"sid"` + Username string `json:"username"` + Domain string `json:"domain"` + SessionID uint32 `json:"session_id"` + IntegrityLevel string `json:"integrity_level"` + IsWOW64 bool `json:"is_wow64"` + IsPackaged bool `json:"is_packaged"` + IsProtected bool `json:"is_protected"` + Ancestors []string `json:"ancestors"` +} + +func newAlertProcess(e *event.Event) *alertProcess { + if e.PS == nil { + return nil + } + proc := &alertProcess{ + PID: e.PS.PID, + TID: e.Tid, + PPID: e.PS.Ppid, + Name: e.PS.Name, + Exe: e.PS.Exe, + Cmdline: e.PS.Cmdline, + Cwd: e.PS.Cwd, + SID: e.PS.SID, + Username: e.PS.Username, + Domain: e.PS.Domain, + SessionID: e.PS.SessionID, + IntegrityLevel: e.PS.TokenIntegrityLevel, + IsWOW64: e.PS.IsWOW64, + IsPackaged: e.PS.IsPackaged, + IsProtected: e.PS.IsProtected, + Ancestors: make([]string, 0), + } + proc.Ancestors = append(proc.Ancestors, e.PS.Ancestors()...) + if e.PS.Parent != nil { + proc.Pname = e.PS.Parent.Name + proc.Pcmdline = e.PS.Parent.Cmdline + } + return proc +} + +func alertCallstack(e *event.Event) []string { + callstack := make([]string, 0, len(e.Callstack)) + for i := range e.Callstack { + frame := e.Callstack[len(e.Callstack)-i-1] + callstack = append(callstack, fmt.Sprintf("%v %s!%s", frame.Addr, frame.Module, frame.Symbol)) + } + return callstack +} diff --git a/pkg/pe/types_linux.go b/pkg/pe/types_linux.go deleted file mode 100644 index 767bcaa34..000000000 --- a/pkg/pe/types_linux.go +++ /dev/null @@ -1,36 +0,0 @@ -//go:build linux - -/* - * Copyright 2026 by Mostafa Moradian - * https://www.fibratus.io - * All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package pe - -import "fmt" - -// Sec contains section attributes. On Linux this is only used so -// shared filter foreach helpers can compile against pe.Sec. -type Sec struct { - Name string - Size uint32 - Entropy float64 - Md5 string -} - -func (s Sec) String() string { - return fmt.Sprintf("Name: %s, Size: %d, Entropy: %f, Md5: %s", s.Name, s.Size, s.Entropy, s.Md5) -} diff --git a/pkg/ps/process_key.go b/pkg/ps/process_key.go deleted file mode 100644 index 250edf1b0..000000000 --- a/pkg/ps/process_key.go +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright 2026 by Mostafa Moradian - * https://www.fibratus.io - * All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ps - -// ProcessKey uniquely identifies a process instance across PID reuse. -type ProcessKey struct { - PID uint32 - StartBootTime uint64 -} diff --git a/pkg/ps/snapshotter_linux.go b/pkg/ps/snapshotter_linux.go index 37b049397..d1f49bcb7 100644 --- a/pkg/ps/snapshotter_linux.go +++ b/pkg/ps/snapshotter_linux.go @@ -36,12 +36,11 @@ type Snapshotter interface { Remove(*event.Event) error // Find attempts to retrieve process state for the specified process identifier. Find(pid uint64) (bool, *pstypes.PS) - // FindAndPut attempts to retrieve process state and updates the snapshot when found. + // FindAndPut retrieves process state. Procfs fallback enrichment will be added + // when Linux capture is wired. FindAndPut(pid uint64) *pstypes.PS // Put inserts the process state into the snapshotter. Put(*pstypes.PS) - // UpsertSnapshot inserts or replaces process state. - UpsertSnapshot(*pstypes.PS) // Size returns the total number of process state items. Size() uint32 // Close closes the process snapshotter and disposes allocated resources. @@ -49,7 +48,7 @@ type Snapshotter interface { // AddThread builds thread state from the event representation. AddThread(*event.Event) error // RemoveThread removes the thread from the given process. - RemoveThread(pid uint64, tid uint32) error + RemoveThread(pid uint64, tid uint64) error // AddMmap adds a memory mapping to the process state. AddMmap(*event.Event) error // RemoveMmap removes a memory mapping at the given base address. @@ -90,10 +89,6 @@ func (s *snapshotter) Put(ps *pstypes.PS) { s.procs[ps.PID] = ps } -func (s *snapshotter) UpsertSnapshot(ps *pstypes.PS) { - s.Put(ps) -} - func (s *snapshotter) Write(evt *event.Event) error { if evt == nil || evt.PS == nil { return nil @@ -138,7 +133,7 @@ func (s *snapshotter) AddThread(evt *event.Event) error { return nil } -func (s *snapshotter) RemoveThread(pid uint64, tid uint32) error { +func (s *snapshotter) RemoveThread(pid uint64, tid uint64) error { ok, ps := s.Find(pid) if !ok || ps == nil { return nil diff --git a/pkg/ps/types/types_linux.go b/pkg/ps/types/types_linux.go index d70a71ffc..290c4e92f 100644 --- a/pkg/ps/types/types_linux.go +++ b/pkg/ps/types/types_linux.go @@ -21,60 +21,73 @@ package types import ( + "encoding/binary" "fmt" - "strings" + "hash/fnv" "sync" "time" "github.com/rabbitstack/fibratus/pkg/util/va" ) -// PE is a placeholder for PE metadata on Linux builds. -// Linux process images are ELF; this field exists so shared -// formatters/templates compile without Windows PE types. -type PE struct{} - -func (p *PE) String() string { return "" } - +// PS encapsulates Linux process state and its allocated resources. type PS struct { sync.RWMutex - PID uint64 `json:"pid"` - Ppid uint64 `json:"ppid"` - Name string `json:"name"` - Cmdline string `json:"comm"` - Exe string `json:"exe"` - Cwd string `json:"cwd"` - Args []string `json:"args"` - StartTime time.Time `json:"started"` - StartBootTime uint64 `json:"start_boot_time"` - UID uint32 `json:"uid"` - GID uint32 `json:"gid"` - Username string `json:"username"` - Domain string `json:"domain"` - SID string `json:"sid"` - SessionID uint32 `json:"session_id"` - TokenIntegrityLevel string `json:"token_integrity_level"` - TokenElevationType string `json:"token_elevation_type"` - IsTokenElevated bool `json:"is_token_elevated"` - IsWOW64 bool `json:"is_wow_64"` - IsPackaged bool `json:"is_packaged"` - IsProtected bool `json:"is_protected"` - Envs map[string]string `json:"envs"` - Parent *PS `json:"parent"` - Threads map[uint32]Thread `json:"-"` - Mmaps []Mmap `json:"mmaps"` - Modules []Module `json:"modules"` - PE *PE `json:"-"` + // PID is the thread group identifier. It is also the thread identifier of the main thread. + PID uint64 `json:"pid"` + // Ppid is the thread group identifier of the parent process. + Ppid uint64 `json:"ppid"` + // Name is the process name. + Name string `json:"name"` + // Cmdline is the full process command line. + Cmdline string `json:"comm"` + // Exe is the full path to the process executable. + Exe string `json:"exe"` + // Cwd is the current working directory of the process. + Cwd string `json:"cwd"` + // Args contains the process command-line arguments. + Args []string `json:"args"` + // StartTime is the wall-clock time when the process started. + StartTime time.Time `json:"started"` + // StartBootTime is the process start time measured from system boot. + StartBootTime uint64 `json:"start_boot_time"` + // UID is the real user identifier of the process. + UID uint32 `json:"uid"` + // GID is the real group identifier of the process. + GID uint32 `json:"gid"` + // Username is the name associated with UID. + Username string `json:"username"` + // Envs contains process environment variables indexed by name. + Envs map[string]string `json:"envs"` + // Parent references the parent process state when it is available. + Parent *PS `json:"parent"` + // Threads contains the threads that belong to this process. + Threads map[uint64]Thread `json:"-"` + // Mmaps contains the process memory mappings, including shared objects. + Mmaps []Mmap `json:"mmaps"` } +// UUID returns a stable identifier for this process instance. +func (ps *PS) UUID() uint64 { + var key [16]byte + binary.LittleEndian.PutUint64(key[:8], ps.PID) + binary.LittleEndian.PutUint64(key[8:], ps.StartBootTime) + h := fnv.New64a() + _, _ = h.Write(key[:]) + return h.Sum64() +} + +// String returns a string representation of the process state. func (ps *PS) String() string { return fmt.Sprintf("Pid: %d\nPpid: %d\nName: %s\nCmdline: %s\nExe: %s", ps.PID, ps.Ppid, ps.Name, ps.Cmdline, ps.Exe) } +// StringShort returns a compact string representation of the process state. func (ps *PS) StringShort() string { return ps.String() } +// Ancestors returns process ancestors as image name and process identifier pairs. func (ps *PS) Ancestors() []string { var ancestors []string Walk(func(parent *PS) { @@ -83,50 +96,56 @@ func (ps *PS) Ancestors() []string { return ancestors } +// Thread stores identifiers for a Linux thread. type Thread struct { - Tid uint32 - Pid uint64 - StartAddress va.Address - UstackBase va.Address - UstackLimit va.Address - KstackBase va.Address - KstackLimit va.Address -} - -type Module struct { - Name string - BaseAddress va.Address - Size uint64 - Checksum uint32 + // Tid is the thread identifier. + Tid uint64 + // Pid is the thread group identifier to which the thread belongs. + Pid uint64 } +// Mmap stores information about a process memory mapping. type Mmap struct { + // BaseAddress is the starting virtual address of the mapping. BaseAddress va.Address - Size uint64 - Protection uint32 - Type string - File string + // Size is the mapping size in bytes. + Size uint64 + // Protection is the mapping protection bitmask. + Protection uint32 + // Type describes the mapping type. + Type string + // File is the path backing the mapping, if any. + File string } +// ProtectMask returns the mapping protection in mask notation. func (m *Mmap) ProtectMask() string { return "" } +// AddThread adds a thread to the process state. func (ps *PS) AddThread(thread Thread) { + ps.Lock() + defer ps.Unlock() if ps.Threads == nil { - ps.Threads = make(map[uint32]Thread) + ps.Threads = make(map[uint64]Thread) } ps.Threads[thread.Tid] = thread } -func (ps *PS) RemoveThread(tid uint32) { +// RemoveThread removes a thread from the process state. +func (ps *PS) RemoveThread(tid uint64) { + ps.Lock() + defer ps.Unlock() delete(ps.Threads, tid) } +// AddMmap adds a memory mapping to the process state. func (ps *PS) AddMmap(mmap Mmap) { ps.Mmaps = append(ps.Mmaps, mmap) } +// RemoveMmap removes the memory mapping at the specified address. func (ps *PS) RemoveMmap(addr va.Address) { for i, mmap := range ps.Mmaps { if mmap.BaseAddress == addr { @@ -136,6 +155,7 @@ func (ps *PS) RemoveMmap(addr va.Address) { } } +// FindMmap returns the memory mapping at the specified address. func (ps *PS) FindMmap(addr va.Address) *Mmap { for i := range ps.Mmaps { if ps.Mmaps[i].BaseAddress == addr { @@ -144,7 +164,3 @@ func (ps *PS) FindMmap(addr va.Address) *Mmap { } return nil } - -func (ps *PS) IsSvchost() bool { - return strings.EqualFold(ps.Name, "svchost.exe") -} diff --git a/pkg/util/key/key_linux.go b/pkg/ps/types/types_linux_test.go similarity index 68% rename from pkg/util/key/key_linux.go rename to pkg/ps/types/types_linux_test.go index ba9fb74ab..981c7478b 100644 --- a/pkg/util/key/key_linux.go +++ b/pkg/ps/types/types_linux_test.go @@ -18,6 +18,18 @@ * limitations under the License. */ -package key +package types -var RegistryValueTypes = map[uint32]string{} +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +func TestPSUUID(t *testing.T) { + process := &PS{PID: 42, StartBootTime: 100} + reusedPID := &PS{PID: 42, StartBootTime: 200} + + require.Equal(t, process.UUID(), process.UUID()) + require.NotEqual(t, process.UUID(), reusedPID.UUID()) +} diff --git a/pkg/util/colorizer/colorizer_stub.go b/pkg/util/colorizer/colorizer_linux.go similarity index 97% rename from pkg/util/colorizer/colorizer_stub.go rename to pkg/util/colorizer/colorizer_linux.go index dbf2e6a41..190af18c9 100644 --- a/pkg/util/colorizer/colorizer_stub.go +++ b/pkg/util/colorizer/colorizer_linux.go @@ -1,4 +1,4 @@ -//go:build !windows +//go:build linux /* * Copyright 2026 by Mostafa Moradian diff --git a/pkg/util/log/logger.go b/pkg/util/log/logger_windows.go similarity index 99% rename from pkg/util/log/logger.go rename to pkg/util/log/logger_windows.go index 452b15940..c9f32353d 100644 --- a/pkg/util/log/logger.go +++ b/pkg/util/log/logger_windows.go @@ -1,5 +1,3 @@ -//go:build windows - /* * Copyright 2019-2020 by Nedim Sabic Sabic * https://www.fibratus.io @@ -24,15 +22,16 @@ import ( "errors" "expvar" "fmt" + "io" + "os" + "path/filepath" + "github.com/rabbitstack/fibratus/pkg/sys" "github.com/rabbitstack/fibratus/pkg/util/log/rotate" fs "github.com/rifflock/lfshook" "github.com/saferwall/pe/log" "github.com/sirupsen/logrus" "golang.org/x/sys/windows" - "io" - "os" - "path/filepath" ) var ( diff --git a/pkg/util/log/logger_test.go b/pkg/util/log/logger_windows_test.go similarity index 99% rename from pkg/util/log/logger_test.go rename to pkg/util/log/logger_windows_test.go index 928befd38..749932651 100644 --- a/pkg/util/log/logger_test.go +++ b/pkg/util/log/logger_windows_test.go @@ -19,10 +19,11 @@ package log import ( - "github.com/sirupsen/logrus" - "github.com/stretchr/testify/require" "os" "testing" + + "github.com/sirupsen/logrus" + "github.com/stretchr/testify/require" ) func TestInitFromConfig(t *testing.T) { diff --git a/pkg/util/ntstatus/status_linux.go b/pkg/util/ntstatus/status_linux.go deleted file mode 100644 index 59b931d0e..000000000 --- a/pkg/util/ntstatus/status_linux.go +++ /dev/null @@ -1,35 +0,0 @@ -//go:build linux - -/* - * Copyright 2026 by Mostafa Moradian - * https://www.fibratus.io - * All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ntstatus - -import "fmt" - -// Success determines the success system message -const Success = "Success" - -// FormatMessage resolves a status code to a human-readable message. -// On Linux this returns a hex representation for non-zero codes. -func FormatMessage(status uint32) string { - if status == 0 { - return Success - } - return fmt.Sprintf("0x%x", status) -} From b391cf2afd45df2f202834b3020e579aec017148 Mon Sep 17 00:00:00 2001 From: Mostafa Moradian Date: Wed, 12 Aug 2026 15:01:49 +0200 Subject: [PATCH 27/28] refactor(platform): align local transports and file layout Use UNIX domain sockets for Linux local API clients while retaining named pipes on Windows, with transport-specific coverage. Rename alert, process snapshotter, mock, and NTSTATUS files to match their platform responsibilities. --- ...{alert_process_linux.go => alert_linux.go} | 0 ...rt_process_windows.go => alert_windows.go} | 0 pkg/api/listener.go | 4 +- pkg/api/listener_linux.go | 11 +- pkg/api/listener_linux_test.go | 50 ++ pkg/ps/snapshotter.go | 71 -- pkg/ps/snapshotter_impl_windows.go | 756 +++++++++++++++++ ...er_mock.go => snapshotter_mock_windows.go} | 0 pkg/ps/snapshotter_windows.go | 777 ++---------------- .../ntstatus/{status_windows.go => status.go} | 0 pkg/util/rest/rest.go | 7 +- pkg/util/rest/rest_linux_test.go | 55 ++ pkg/util/rest/rest_test.go | 29 - pkg/util/rest/rest_windows_test.go | 57 ++ 14 files changed, 977 insertions(+), 840 deletions(-) rename pkg/alertsender/{alert_process_linux.go => alert_linux.go} (100%) rename pkg/alertsender/{alert_process_windows.go => alert_windows.go} (100%) create mode 100644 pkg/api/listener_linux_test.go delete mode 100644 pkg/ps/snapshotter.go create mode 100644 pkg/ps/snapshotter_impl_windows.go rename pkg/ps/{snapshotter_mock.go => snapshotter_mock_windows.go} (100%) rename pkg/util/ntstatus/{status_windows.go => status.go} (100%) create mode 100644 pkg/util/rest/rest_linux_test.go create mode 100644 pkg/util/rest/rest_windows_test.go diff --git a/pkg/alertsender/alert_process_linux.go b/pkg/alertsender/alert_linux.go similarity index 100% rename from pkg/alertsender/alert_process_linux.go rename to pkg/alertsender/alert_linux.go diff --git a/pkg/alertsender/alert_process_windows.go b/pkg/alertsender/alert_windows.go similarity index 100% rename from pkg/alertsender/alert_process_windows.go rename to pkg/alertsender/alert_windows.go diff --git a/pkg/api/listener.go b/pkg/api/listener.go index 433a9b9a6..f9eac573f 100644 --- a/pkg/api/listener.go +++ b/pkg/api/listener.go @@ -46,8 +46,8 @@ func makeTCPListener(addr string) (net.Listener, error) { return net.Listen("tcp", addr) } -// DialPipe creates a dialer to be used with the http.Client to connect to a named pipe. -func DialPipe(pipePath string) func(context.Context, string, string) (net.Conn, error) { +// DialLocalTransport creates a dialer for the Windows named pipe transport. +func DialLocalTransport(pipePath string) func(context.Context, string, string) (net.Conn, error) { npipe := transformPipePath(pipePath) return func(ctx context.Context, _, _ string) (net.Conn, error) { return winio.DialPipeContext(ctx, npipe) diff --git a/pkg/api/listener_linux.go b/pkg/api/listener_linux.go index a3aa832e2..cd145dc41 100644 --- a/pkg/api/listener_linux.go +++ b/pkg/api/listener_linux.go @@ -22,13 +22,14 @@ package api import ( "context" - "fmt" "net" + "strings" ) -// DialPipe is unavailable on Linux. The HTTP API uses TCP transports instead. -func DialPipe(pipePath string) func(context.Context, string, string) (net.Conn, error) { - return func(context.Context, string, string) (net.Conn, error) { - return nil, fmt.Errorf("named pipe transport %q is not supported on linux", pipePath) +// DialLocalTransport creates a dialer for the Linux UNIX domain socket transport. +func DialLocalTransport(path string) func(context.Context, string, string) (net.Conn, error) { + path = strings.TrimPrefix(path, "unix://") + return func(ctx context.Context, _, _ string) (net.Conn, error) { + return (&net.Dialer{}).DialContext(ctx, "unix", path) } } diff --git a/pkg/api/listener_linux_test.go b/pkg/api/listener_linux_test.go new file mode 100644 index 000000000..ef6d49a4f --- /dev/null +++ b/pkg/api/listener_linux_test.go @@ -0,0 +1,50 @@ +//go:build linux + +/* + * Copyright 2026 by Mostafa Moradian + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package api + +import ( + "context" + "net" + "path/filepath" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestDialLocalTransport(t *testing.T) { + path := filepath.Join(t.TempDir(), "fibratus.sock") + listener, err := net.Listen("unix", path) + require.NoError(t, err) + t.Cleanup(func() { require.NoError(t, listener.Close()) }) + + accepted := make(chan net.Conn, 1) + go func() { + conn, err := listener.Accept() + if err == nil { + accepted <- conn + } + }() + + conn, err := DialLocalTransport("unix://"+path)(context.Background(), "", "") + require.NoError(t, err) + require.NoError(t, conn.Close()) + require.NoError(t, (<-accepted).Close()) +} diff --git a/pkg/ps/snapshotter.go b/pkg/ps/snapshotter.go deleted file mode 100644 index 34f7997fa..000000000 --- a/pkg/ps/snapshotter.go +++ /dev/null @@ -1,71 +0,0 @@ -//go:build windows - -/* - * Copyright 2020-2021 by Nedim Sabic Sabic - * https://www.fibratus.io - * All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ps - -import ( - "github.com/rabbitstack/fibratus/pkg/event" - pstypes "github.com/rabbitstack/fibratus/pkg/ps/types" - "github.com/rabbitstack/fibratus/pkg/util/va" -) - -// Snapshotter is the interface that exposes a set of methods all process snapshotters have to satisfy. It stores the state -// of all running processes in the system including its threads, dynamically loaded libraries, handles/file descriptors -// and other metadata. -type Snapshotter interface { - // Write appends a new process state to the snapshotter. It takes as an input the inbound event to fetch - // the basic data, but also enriches the process' state with extra metadata such as process' env variables, PE - // metadata for Windows binaries and so on. - Write(*event.Event) error - // AddThread builds thread state from the event representation. - AddThread(*event.Event) error - // AddModule builds module state from the event representation. - AddModule(*event.Event) error - // RemoveThread removes the thread from the given process. - RemoveThread(pid uint32, tid uint32) error - // RemoveModule removes the module the given process. - RemoveModule(pid uint32, addr va.Address) error - // AddMmap adds a new memory mapping (data memory-mapped file, image, or pagefile) to this process state. - AddMmap(*event.Event) error - // RemoveMmap removes memory mapping at the given base address. - RemoveMmap(pid uint32, addr va.Address) error - // WriteFromCapture appends a new process state to the snapshotter from the captured event. - WriteFromCapture(evt *event.Event) error - // Remove deletes process's state from the snapshotter. - Remove(evt *event.Event) error - // Find attempts to retrieve process' state for the specified process identifier. Returns true - // if the process was find in the state. Otherwise, returns false and constructs a fresh process - // state by querying the OS via API functions. - Find(pid uint32) (bool, *pstypes.PS) - // FindModule traverses loaded modules of all processes in the snapshot and - // if there is module with the specified base address, it returns its metadata. - FindModule(addr va.Address) (bool, *pstypes.Module) - // FindAllModules finds all unique modules across the snapshotter state. - FindAllModules() map[string]pstypes.Module - // FindAndPut attempts to retrieve process' state for the specified process identifier. - // If the process is found, the snapshotter state is updated with the new process. - FindAndPut(pid uint32) *pstypes.PS - // Put inserts the process state into snapshotter. - Put(*pstypes.PS) - // Size returns the total number of process state items. - Size() uint32 - // Close closes process snapshotter and disposes all allocated resources. - Close() error -} diff --git a/pkg/ps/snapshotter_impl_windows.go b/pkg/ps/snapshotter_impl_windows.go new file mode 100644 index 000000000..b17179ad4 --- /dev/null +++ b/pkg/ps/snapshotter_impl_windows.go @@ -0,0 +1,756 @@ +/* + * Copyright 2019-2020 by Nedim Sabic Sabic + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ps + +import ( + "expvar" + "path/filepath" + "strconv" + "strings" + "sync" + "time" + + "github.com/rabbitstack/fibratus/pkg/sys" + "github.com/rabbitstack/fibratus/pkg/util/va" + "golang.org/x/sys/windows" + + "github.com/rabbitstack/fibratus/pkg/config" + "github.com/rabbitstack/fibratus/pkg/event" + "github.com/rabbitstack/fibratus/pkg/event/params" + "github.com/rabbitstack/fibratus/pkg/handle" + htypes "github.com/rabbitstack/fibratus/pkg/handle/types" + "github.com/rabbitstack/fibratus/pkg/pe" + pstypes "github.com/rabbitstack/fibratus/pkg/ps/types" + log "github.com/sirupsen/logrus" +) + +// SystemPID designates the pid of the system process that acts as the container for system threads +const SystemPID uint32 = 4 + +var ( + // reapPeriod specifies the interval for triggering the housekeeping of dead processes + reapPeriod = time.Minute * 2 + + processLookupFailureCount = expvar.NewMap("process.lookup.failure.count") + reapedProcesses = expvar.NewInt("process.reaped") + processCount = expvar.NewInt("process.count") + threadCount = expvar.NewInt("process.thread.count") + moduleCount = expvar.NewInt("process.module.count") + mmapCount = expvar.NewInt("process.mmap.count") + pebReadErrors = expvar.NewInt("process.peb.read.errors") + processEnrichments = expvar.NewInt("process.enrichments") +) + +type snapshotter struct { + mu sync.RWMutex + procs map[uint32]*pstypes.PS + dirty map[uint32]*pstypes.PS + dmu sync.RWMutex + quit chan struct{} + config *config.Config + hsnap handle.Snapshotter + capture bool +} + +// NewSnapshotter returns a new instance of the process snapshotter. +func NewSnapshotter(hsnap handle.Snapshotter, config *config.Config) Snapshotter { + s := &snapshotter{ + procs: make(map[uint32]*pstypes.PS), + dirty: make(map[uint32]*pstypes.PS), + quit: make(chan struct{}, 1), + config: config, + hsnap: hsnap, + } + + s.mu.Lock() + defer s.mu.Unlock() + + s.hsnap.RegisterCreateCallback(s.onHandleCreated) + s.hsnap.RegisterDestroyCallback(s.onHandleDestroyed) + + go s.gcDeadProcesses() + + return s +} + +// NewSnapshotterFromCapture restores the snapshotter state from the cap file. +func NewSnapshotterFromCapture(hsnap handle.Snapshotter, config *config.Config) Snapshotter { + s := &snapshotter{ + procs: make(map[uint32]*pstypes.PS), + dirty: make(map[uint32]*pstypes.PS), + quit: make(chan struct{}, 1), + config: config, + hsnap: hsnap, + capture: true, + } + + s.hsnap.RegisterCreateCallback(s.onHandleCreated) + s.hsnap.RegisterDestroyCallback(s.onHandleDestroyed) + + return s +} + +func (s *snapshotter) WriteFromCapture(e *event.Event) error { + switch e.Type { + case event.CreateProcess, event.ProcessRundown: + s.mu.Lock() + defer s.mu.Unlock() + proc := e.PS + if proc == nil { + return nil + } + pid, err := e.Params.GetPid() + if err != nil { + return err + } + ppid, err := e.Params.GetPpid() + if err != nil { + return err + } + if proc.PID == proc.Ppid || + (e.IsProcessRundown() && pid == sys.InvalidProcessID) { + return nil + } + if e.IsProcessRundown() { + proc.Parent = s.procs[ppid] + } else { + proc, err = s.newProcState(pid, ppid, e) + if err != nil { + return err + } + } + s.procs[pid] = proc + case event.CreateThread, event.ThreadRundown: + return s.AddThread(e) + case event.LoadModule, event.ModuleRundown: + return s.AddModule(e) + } + return nil +} + +func (s *snapshotter) Write(e *event.Event) error { + s.mu.Lock() + defer s.mu.Unlock() + processCount.Add(1) + + pid, err := e.Params.GetPid() + if err != nil { + return err + } + ppid, err := e.Params.GetPpid() + if err != nil { + return err + } + + proc, err := s.newProcState(pid, ppid, e) + if ps := s.procs[pid]; ps == nil && (e.IsCreateProcessInternal() || e.IsProcessRundownInternal()) { + // only modify the state if there is no process derived from the NT kernel logger process events + s.procs[pid] = proc + } else if ps, ok := s.procs[pid]; ok && (e.IsCreateProcessInternal() || e.IsProcessRundownInternal()) && ps.IsCreatedFromSystemLogger { + // process state derived from the core kernel events exists - enrich it + ps.TokenIntegrityLevel = proc.TokenIntegrityLevel + ps.TokenElevationType = proc.TokenElevationType + ps.IsTokenElevated = proc.IsTokenElevated + if strings.EqualFold(ps.Name, filepath.Base(proc.Exe)) && len(proc.Exe) > len(ps.Exe) { + // prefer full executable path + ps.Exe = proc.Exe + } + s.procs[pid] = ps + } else if ps, ok := s.procs[pid]; ok && (e.IsCreateProcess() || e.IsProcessRundown()) && !ps.IsCreatedFromSystemLogger { + // enrich the existing process state with the newly arrived NT kernel logger process events + // but obtain the integrity level and executable path from the previous proc state + processEnrichments.Add(1) + proc.TokenIntegrityLevel = ps.TokenIntegrityLevel + proc.TokenElevationType = ps.TokenElevationType + proc.IsTokenElevated = ps.IsTokenElevated + + if strings.EqualFold(proc.Name, filepath.Base(ps.Exe)) && len(ps.Exe) > len(proc.Exe) { + // prefer full executable path + proc.Exe = ps.Exe + e.AppendParam(params.Exe, params.Path, ps.Exe) + } + + // if the process UUID has been initialized when + // the internal event arrived, reassign it to the + // current process state + proc.AssignUUID(ps) + + e.AppendParam(params.ProcessTokenIntegrityLevel, params.AnsiString, ps.TokenIntegrityLevel) + e.AppendParam(params.ProcessTokenElevationType, params.AnsiString, ps.TokenElevationType) + e.AppendParam(params.ProcessTokenIsElevated, params.Bool, ps.IsTokenElevated) + + s.procs[pid] = proc + } else { + // in all other cases append the process state + s.procs[pid] = proc + } + + // assign process state to the event + e.PS = proc + + return err +} + +func (s *snapshotter) AddThread(e *event.Event) error { + pid, err := e.Params.GetPid() + if err != nil { + return err + } + threadCount.Add(1) + + s.mu.Lock() + defer s.mu.Unlock() + proc, ok := s.procs[pid] + if !ok { + return nil + } + + thread := pstypes.Thread{} + thread.Tid, _ = e.Params.GetTid() + thread.UstackBase = e.Params.TryGetAddress(params.UstackBase) + thread.UstackLimit = e.Params.TryGetAddress(params.UstackLimit) + thread.KstackBase = e.Params.TryGetAddress(params.KstackBase) + thread.KstackLimit = e.Params.TryGetAddress(params.KstackLimit) + thread.IOPrio, _ = e.Params.GetUint8(params.IOPrio) + thread.BasePrio, _ = e.Params.GetUint8(params.BasePrio) + thread.PagePrio, _ = e.Params.GetUint8(params.PagePrio) + thread.StartAddress = e.Params.TryGetAddress(params.StartAddress) + + proc.AddThread(thread) + + return nil +} + +func (s *snapshotter) AddModule(e *event.Event) error { + pid, err := e.Params.GetPid() + if err != nil { + return err + } + s.mu.Lock() + defer s.mu.Unlock() + + if pid == 0 && e.IsModuleRundown() { + // assume system process if pid is zero + pid = SystemPID + } + proc, ok := s.procs[pid] + if !ok { + return nil + } + + module := pstypes.Module{} + module.Size, _ = e.Params.GetUint64(params.ModuleSize) + module.Checksum, _ = e.Params.GetUint32(params.ModuleCheckSum) + module.TimedateStamp, _ = e.Params.GetUint32(params.ModuleTimeDateStamp) + module.Name = e.GetParamAsString(params.ModulePath) + module.BaseAddress = e.Params.TryGetAddress(params.ModuleBase) + module.DefaultBaseAddress = e.Params.TryGetAddress(params.ModuleDefaultBase) + + if e.IsLoadModuleInternal() { + proc.AddModule(module) + return nil + } + + moduleCount.Add(1) + + module.SignatureLevel, _ = e.Params.GetUint32(params.ModuleSignatureLevel) + module.SignatureType, _ = e.Params.GetUint32(params.ModuleSignatureType) + + if strings.EqualFold(proc.Name, filepath.Base(module.Name)) && len(proc.Exe) < len(module.Name) { + // if the module is loaded for the process executable, and + // we don't have the full executable path, override with + // the one from the Module path + proc.Exe = module.Name + } + + proc.AddModule(module) + + return nil +} + +func (s *snapshotter) RemoveThread(pid uint32, tid uint32) error { + s.mu.Lock() + defer s.mu.Unlock() + proc, ok := s.procs[pid] + if !ok { + return nil + } + proc.RemoveThread(tid) + threadCount.Add(-1) + return nil +} + +func (s *snapshotter) RemoveModule(pid uint32, addr va.Address) error { + s.mu.Lock() + defer s.mu.Unlock() + proc, ok := s.procs[pid] + if !ok { + return nil + } + proc.RemoveModule(addr) + moduleCount.Add(-1) + return nil +} + +func (s *snapshotter) FindModule(addr va.Address) (bool, *pstypes.Module) { + s.mu.RLock() + defer s.mu.RUnlock() + for _, proc := range s.procs { + for _, mod := range proc.Modules { + if mod.BaseAddress == addr { + return true, &mod + } + } + } + return false, nil +} + +func (s *snapshotter) FindAllModules() map[string]pstypes.Module { + s.mu.RLock() + defer s.mu.RUnlock() + mods := make(map[string]pstypes.Module) + for _, proc := range s.procs { + for _, mod := range proc.Modules { + if _, ok := mods[mod.Name]; ok { + continue + } + mods[mod.Name] = mod + } + } + return mods +} + +func (s *snapshotter) AddMmap(e *event.Event) error { + s.mu.Lock() + defer s.mu.Unlock() + proc, ok := s.procs[e.PID] + if !ok { + return nil + } + + mmapCount.Add(1) + + mmap := pstypes.Mmap{} + mmap.File = e.GetParamAsString(params.FilePath) + mmap.BaseAddress = e.Params.TryGetAddress(params.FileViewBase) + mmap.Size, _ = e.Params.GetUint64(params.FileViewSize) + mmap.Protection, _ = e.Params.GetUint32(params.MemProtect) + mmap.Type = e.GetParamAsString(params.FileViewSectionType) + + proc.AddMmap(mmap) + + return nil +} + +func (s *snapshotter) RemoveMmap(pid uint32, addr va.Address) error { + s.mu.Lock() + defer s.mu.Unlock() + proc, ok := s.procs[pid] + if !ok { + return nil + } + mmapCount.Add(-1) + proc.RemoveMmap(addr) + return nil +} + +func (s *snapshotter) Close() error { + s.quit <- struct{}{} + return nil +} + +func (s *snapshotter) newProcState(pid, ppid uint32, e *event.Event) (*pstypes.PS, error) { + if e.IsCreateProcessInternal() || e.IsProcessRundownInternal() { + proc := &pstypes.PS{ + PID: pid, + Ppid: ppid, + Exe: e.GetParamAsString(params.Exe), + Name: filepath.Base(e.GetParamAsString(params.Exe)), + TokenIntegrityLevel: e.GetParamAsString(params.ProcessTokenIntegrityLevel), + TokenElevationType: e.GetParamAsString(params.ProcessTokenElevationType), + IsTokenElevated: e.Params.TryGetBool(params.ProcessTokenIsElevated), + Threads: make(map[uint32]pstypes.Thread), + Modules: make([]pstypes.Module, 0), + Handles: make([]htypes.Handle, 0), + Mmaps: make([]pstypes.Mmap, 0), + } + + return proc, nil + } + + proc := pstypes.New( + pid, + ppid, + e.GetParamAsString(params.ProcessName), + e.GetParamAsString(params.Cmdline), + e.GetParamAsString(params.Exe), + e.Params.MustGetSID(), + e.Params.MustGetUint32(params.SessionID), + ) + + proc.Parent = s.procs[ppid] + proc.StartTime, _ = e.Params.GetTime(params.StartTime) + proc.IsWOW64 = (e.Params.MustGetUint32(params.ProcessFlags) & event.PsWOW64) != 0 + proc.IsPackaged = (e.Params.MustGetUint32(params.ProcessFlags) & event.PsPackaged) != 0 + proc.IsProtected = (e.Params.MustGetUint32(params.ProcessFlags) & event.PsProtected) != 0 + proc.IsCreatedFromSystemLogger = true + + if !s.capture { + if proc.Username != "" { + e.AppendParam(params.Username, params.UnicodeString, proc.Username) + } + if proc.Domain != "" { + e.AppendParam(params.Domain, params.UnicodeString, proc.Domain) + } + // retrieve process handles + var err error + proc.Handles, err = s.hsnap.FindHandles(pid) + if err != nil { + return proc, err + } + } + + // return early if we're reading from the capture file + if s.capture { + // reset username/domain from captured event parameters + proc.Domain = e.GetParamAsString(params.Domain) + proc.Username = e.GetParamAsString(params.Username) + return proc, nil + } + + // retrieve Portable Executable data + var err error + proc.PE, err = pe.ParseFileWithConfig(proc.Exe, s.config.PE) + if err != nil { + return proc, err + } + + // try to read the PEB (Process Environment Block) + // to access environment variables and the process + // current working directory + access := uint32(windows.PROCESS_QUERY_INFORMATION | windows.PROCESS_VM_READ) + process, err := windows.OpenProcess(access, false, pid) + if err != nil { + process, err = windows.OpenProcess(windows.PROCESS_QUERY_INFORMATION, false, pid) + if err != nil { + return proc, nil + } + } + //nolint:errcheck + defer windows.CloseHandle(process) + + // query token attributes if not enriched by internal event + if s.procs[pid] == nil { + var token windows.Token + err = windows.OpenProcessToken(process, windows.TOKEN_QUERY, &token) + if err != nil { + goto readPEB + } + defer token.Close() + + // get process token integrity level + tokenMandatoryLabel, err := sys.GetProcessTokenInformation[windows.Tokenmandatorylabel](token, windows.TokenIntegrityLevel) + if err != nil { + goto readPEB + } + + proc.TokenIntegrityLevel = sys.RidToString(tokenMandatoryLabel.Label.Sid) + proc.IsTokenElevated = token.IsElevated() + + e.AppendParam(params.ProcessTokenIntegrityLevel, params.AnsiString, proc.TokenIntegrityLevel) + e.AppendParam(params.ProcessTokenIsElevated, params.Bool, proc.IsTokenElevated) + } + +readPEB: + // read PEB (Process Environment Block) + peb, err := ReadPEB(process) + if err != nil { + pebReadErrors.Add(1) + return proc, err + } + proc.Envs = peb.GetEnvs() + proc.Cwd = peb.GetCurrentWorkingDirectory() + + return proc, nil +} + +func (s *snapshotter) Remove(e *event.Event) error { + s.mu.Lock() + defer s.mu.Unlock() + pid, err := e.Params.GetPid() + if err != nil { + return err + } + // remove process from primary map and + // move to dirty map. This is required + // to prevent dropping process state from + // events when TerminateProcess event is + // emitted before subsequent events + if proc := s.procs[pid]; proc != nil { + s.dmu.Lock() + defer s.dmu.Unlock() + s.dirty[pid] = proc + // schedule removal + remove := func(pid uint32) func() { + return func() { + s.dmu.Lock() + defer s.dmu.Unlock() + if ps, ok := s.dirty[pid]; ok { + delete(s.dirty, pid) + log.Debugf("dirty process removed: %s. Dirty procs: %d", ps.Name, len(s.dirty)) + } + } + } + time.AfterFunc(time.Second*5, remove(pid)) + } + delete(s.procs, pid) + processCount.Add(-1) + // reset parent if it died after spawning a process + for procID, proc := range s.procs { + if proc.Ppid == pid { + s.procs[procID].Parent = nil + } + } + return nil +} + +func (s *snapshotter) Put(proc *pstypes.PS) { + if proc != nil { + s.mu.Lock() + defer s.mu.Unlock() + s.procs[proc.PID] = proc + } +} + +func (s *snapshotter) FindAndPut(pid uint32) *pstypes.PS { + ok, proc := s.Find(pid) + if !ok { + s.Put(proc) + } + return proc +} + +func (s *snapshotter) Find(pid uint32) (bool, *pstypes.PS) { + s.mu.RLock() + defer s.mu.RUnlock() + ps, ok := s.procs[pid] + if ok { + return true, ps + } + if s.capture || pid == sys.InvalidProcessID { + return false, nil + } + + // check if the process is in dirty map + s.dmu.RLock() + defer s.dmu.RUnlock() + if ps := s.dirty[pid]; ps != nil { + return true, ps + } + + processLookupFailureCount.Add(strconv.Itoa(int(pid)), 1) + + proc := &pstypes.PS{ + PID: pid, + Ppid: sys.InvalidProcessID, + Threads: make(map[uint32]pstypes.Thread), + Modules: make([]pstypes.Module, 0), + Handles: make([]htypes.Handle, 0), + } + + getProcExecutable := func(process windows.Handle) (string, string) { + var size uint32 = windows.MAX_PATH + n := make([]uint16, size) + err := windows.QueryFullProcessImageName(process, 0, &n[0], &size) + if err != nil { + return "", "" + } + return windows.UTF16ToString(n), filepath.Base(windows.UTF16ToString(n)) + } + + access := uint32(windows.PROCESS_QUERY_INFORMATION | windows.PROCESS_VM_READ) + process, err := windows.OpenProcess(access, false, pid) + if err != nil { + // the access to protected / system process can't be achieved + // through `PROCESS_VM_READ` or `PROCESS_QUERY_INFORMATION` flags. + // Try to acquire the process handle again but with restricted access + // rights to be able to obtain other attributes such as the full process's + // Module executable path or process times + process, err = windows.OpenProcess(windows.PROCESS_QUERY_LIMITED_INFORMATION, false, pid) + if err != nil { + return false, nil + } + } + //nolint:errcheck + defer windows.CloseHandle(process) + + // get process executable full path and name + proc.Exe, proc.Name = getProcExecutable(process) + + // consult process parent id + info, err := sys.QueryInformationProcess[windows.PROCESS_BASIC_INFORMATION](process, windows.ProcessBasicInformation) + if err != nil { + return false, proc + } + proc.Ppid = uint32(info.InheritedFromUniqueProcessId) + + // retrieve Portable Executable data + proc.PE, err = pe.ParseFileWithConfig(proc.Exe, s.config.PE) + if err != nil { + return false, proc + } + + // get process times + var ( + ct windows.Filetime + xt windows.Filetime + kt windows.Filetime + ut windows.Filetime + ) + err = windows.GetProcessTimes(process, &ct, &xt, &kt, &ut) + if err != nil { + return false, proc + } + proc.StartTime = time.Unix(0, ct.Nanoseconds()) + + // get process creation attributes + var isWOW64 bool + if err := windows.IsWow64Process(process, &isWOW64); err == nil && isWOW64 { + proc.IsWOW64 = true + } + if isPackaged, err := sys.IsProcessPackaged(process); err == nil && isPackaged { + proc.IsPackaged = true + } + if prot, err := sys.QueryInformationProcess[sys.PsProtection](process, sys.ProcessProtectionInformation); err == nil && prot != nil { + proc.IsProtected = prot.IsProtected() + } + + // get process token attributes + var ( + token windows.Token + tokenUser *windows.Tokenuser + tokenMandatoryLabel *windows.Tokenmandatorylabel + ) + + err = windows.OpenProcessToken(process, windows.TOKEN_QUERY, &token) + if err != nil { + goto readPEB + } + defer token.Close() + tokenUser, err = token.GetTokenUser() + if err != nil { + goto readPEB + } + proc.SID = tokenUser.User.Sid.String() + proc.Username, proc.Domain, _, _ = tokenUser.User.Sid.LookupAccount("") + + // get process token integrity level + tokenMandatoryLabel, err = sys.GetProcessTokenInformation[windows.Tokenmandatorylabel](token, windows.TokenIntegrityLevel) + if err != nil { + goto readPEB + } + + proc.TokenIntegrityLevel = sys.RidToString(tokenMandatoryLabel.Label.Sid) + proc.IsTokenElevated = token.IsElevated() + + // retrieve process handles + proc.Handles, err = s.hsnap.FindHandles(pid) + if err != nil { + goto readPEB + } + +readPEB: + // read PEB (Process Environment Block) + peb, err := ReadPEB(process) + if err != nil { + pebReadErrors.Add(1) + return false, proc + } + proc.Envs = peb.GetEnvs() + proc.Cmdline = peb.GetCommandLine() + proc.SessionID = peb.GetSessionID() + proc.Cwd = peb.GetCurrentWorkingDirectory() + + return false, proc +} + +func (s *snapshotter) Size() uint32 { + s.mu.RLock() + defer s.mu.RUnlock() + return uint32(len(s.procs)) +} + +// gcDeadProcesses periodically scans the map of the snapshot's processes and removes +// any terminated processes from it. This guarantees that any leftovers are cleaned-up +// in case we miss process' terminate events. +func (s *snapshotter) gcDeadProcesses() { + tick := time.NewTicker(reapPeriod) + for { + select { + case <-tick.C: + s.mu.Lock() + ss := len(s.procs) + log.Debugf("scanning for dead processes on the snapshot of %d items", ss) + + for pid := range s.procs { + proc, err := windows.OpenProcess(windows.PROCESS_QUERY_LIMITED_INFORMATION, false, pid) + if err != nil { + continue + } + if !sys.IsProcessRunning(proc) { + delete(s.procs, pid) + } + _ = windows.CloseHandle(proc) + } + + if ss > len(s.procs) { + reaped := ss - len(s.procs) + reapedProcesses.Add(int64(reaped)) + log.Debugf("%d dead process(es) reaped", reaped) + } + s.mu.Unlock() + case <-s.quit: + tick.Stop() + } + } +} + +func (s *snapshotter) onHandleCreated(pid uint32, handle htypes.Handle) { + s.mu.RLock() + ps, ok := s.procs[pid] + s.mu.RUnlock() + if ok { + s.mu.Lock() + defer s.mu.Unlock() + ps.AddHandle(handle) + s.procs[pid] = ps + } +} + +func (s *snapshotter) onHandleDestroyed(pid uint32, rawHandle windows.Handle) { + s.mu.RLock() + ps, ok := s.procs[pid] + s.mu.RUnlock() + if ok { + s.mu.Lock() + defer s.mu.Unlock() + ps.RemoveHandle(rawHandle) + s.procs[pid] = ps + } +} diff --git a/pkg/ps/snapshotter_mock.go b/pkg/ps/snapshotter_mock_windows.go similarity index 100% rename from pkg/ps/snapshotter_mock.go rename to pkg/ps/snapshotter_mock_windows.go diff --git a/pkg/ps/snapshotter_windows.go b/pkg/ps/snapshotter_windows.go index b17179ad4..34f7997fa 100644 --- a/pkg/ps/snapshotter_windows.go +++ b/pkg/ps/snapshotter_windows.go @@ -1,5 +1,7 @@ +//go:build windows + /* - * Copyright 2019-2020 by Nedim Sabic Sabic + * Copyright 2020-2021 by Nedim Sabic Sabic * https://www.fibratus.io * All Rights Reserved. * @@ -19,738 +21,51 @@ package ps import ( - "expvar" - "path/filepath" - "strconv" - "strings" - "sync" - "time" - - "github.com/rabbitstack/fibratus/pkg/sys" - "github.com/rabbitstack/fibratus/pkg/util/va" - "golang.org/x/sys/windows" - - "github.com/rabbitstack/fibratus/pkg/config" "github.com/rabbitstack/fibratus/pkg/event" - "github.com/rabbitstack/fibratus/pkg/event/params" - "github.com/rabbitstack/fibratus/pkg/handle" - htypes "github.com/rabbitstack/fibratus/pkg/handle/types" - "github.com/rabbitstack/fibratus/pkg/pe" pstypes "github.com/rabbitstack/fibratus/pkg/ps/types" - log "github.com/sirupsen/logrus" -) - -// SystemPID designates the pid of the system process that acts as the container for system threads -const SystemPID uint32 = 4 - -var ( - // reapPeriod specifies the interval for triggering the housekeeping of dead processes - reapPeriod = time.Minute * 2 - - processLookupFailureCount = expvar.NewMap("process.lookup.failure.count") - reapedProcesses = expvar.NewInt("process.reaped") - processCount = expvar.NewInt("process.count") - threadCount = expvar.NewInt("process.thread.count") - moduleCount = expvar.NewInt("process.module.count") - mmapCount = expvar.NewInt("process.mmap.count") - pebReadErrors = expvar.NewInt("process.peb.read.errors") - processEnrichments = expvar.NewInt("process.enrichments") + "github.com/rabbitstack/fibratus/pkg/util/va" ) -type snapshotter struct { - mu sync.RWMutex - procs map[uint32]*pstypes.PS - dirty map[uint32]*pstypes.PS - dmu sync.RWMutex - quit chan struct{} - config *config.Config - hsnap handle.Snapshotter - capture bool -} - -// NewSnapshotter returns a new instance of the process snapshotter. -func NewSnapshotter(hsnap handle.Snapshotter, config *config.Config) Snapshotter { - s := &snapshotter{ - procs: make(map[uint32]*pstypes.PS), - dirty: make(map[uint32]*pstypes.PS), - quit: make(chan struct{}, 1), - config: config, - hsnap: hsnap, - } - - s.mu.Lock() - defer s.mu.Unlock() - - s.hsnap.RegisterCreateCallback(s.onHandleCreated) - s.hsnap.RegisterDestroyCallback(s.onHandleDestroyed) - - go s.gcDeadProcesses() - - return s -} - -// NewSnapshotterFromCapture restores the snapshotter state from the cap file. -func NewSnapshotterFromCapture(hsnap handle.Snapshotter, config *config.Config) Snapshotter { - s := &snapshotter{ - procs: make(map[uint32]*pstypes.PS), - dirty: make(map[uint32]*pstypes.PS), - quit: make(chan struct{}, 1), - config: config, - hsnap: hsnap, - capture: true, - } - - s.hsnap.RegisterCreateCallback(s.onHandleCreated) - s.hsnap.RegisterDestroyCallback(s.onHandleDestroyed) - - return s -} - -func (s *snapshotter) WriteFromCapture(e *event.Event) error { - switch e.Type { - case event.CreateProcess, event.ProcessRundown: - s.mu.Lock() - defer s.mu.Unlock() - proc := e.PS - if proc == nil { - return nil - } - pid, err := e.Params.GetPid() - if err != nil { - return err - } - ppid, err := e.Params.GetPpid() - if err != nil { - return err - } - if proc.PID == proc.Ppid || - (e.IsProcessRundown() && pid == sys.InvalidProcessID) { - return nil - } - if e.IsProcessRundown() { - proc.Parent = s.procs[ppid] - } else { - proc, err = s.newProcState(pid, ppid, e) - if err != nil { - return err - } - } - s.procs[pid] = proc - case event.CreateThread, event.ThreadRundown: - return s.AddThread(e) - case event.LoadModule, event.ModuleRundown: - return s.AddModule(e) - } - return nil -} - -func (s *snapshotter) Write(e *event.Event) error { - s.mu.Lock() - defer s.mu.Unlock() - processCount.Add(1) - - pid, err := e.Params.GetPid() - if err != nil { - return err - } - ppid, err := e.Params.GetPpid() - if err != nil { - return err - } - - proc, err := s.newProcState(pid, ppid, e) - if ps := s.procs[pid]; ps == nil && (e.IsCreateProcessInternal() || e.IsProcessRundownInternal()) { - // only modify the state if there is no process derived from the NT kernel logger process events - s.procs[pid] = proc - } else if ps, ok := s.procs[pid]; ok && (e.IsCreateProcessInternal() || e.IsProcessRundownInternal()) && ps.IsCreatedFromSystemLogger { - // process state derived from the core kernel events exists - enrich it - ps.TokenIntegrityLevel = proc.TokenIntegrityLevel - ps.TokenElevationType = proc.TokenElevationType - ps.IsTokenElevated = proc.IsTokenElevated - if strings.EqualFold(ps.Name, filepath.Base(proc.Exe)) && len(proc.Exe) > len(ps.Exe) { - // prefer full executable path - ps.Exe = proc.Exe - } - s.procs[pid] = ps - } else if ps, ok := s.procs[pid]; ok && (e.IsCreateProcess() || e.IsProcessRundown()) && !ps.IsCreatedFromSystemLogger { - // enrich the existing process state with the newly arrived NT kernel logger process events - // but obtain the integrity level and executable path from the previous proc state - processEnrichments.Add(1) - proc.TokenIntegrityLevel = ps.TokenIntegrityLevel - proc.TokenElevationType = ps.TokenElevationType - proc.IsTokenElevated = ps.IsTokenElevated - - if strings.EqualFold(proc.Name, filepath.Base(ps.Exe)) && len(ps.Exe) > len(proc.Exe) { - // prefer full executable path - proc.Exe = ps.Exe - e.AppendParam(params.Exe, params.Path, ps.Exe) - } - - // if the process UUID has been initialized when - // the internal event arrived, reassign it to the - // current process state - proc.AssignUUID(ps) - - e.AppendParam(params.ProcessTokenIntegrityLevel, params.AnsiString, ps.TokenIntegrityLevel) - e.AppendParam(params.ProcessTokenElevationType, params.AnsiString, ps.TokenElevationType) - e.AppendParam(params.ProcessTokenIsElevated, params.Bool, ps.IsTokenElevated) - - s.procs[pid] = proc - } else { - // in all other cases append the process state - s.procs[pid] = proc - } - - // assign process state to the event - e.PS = proc - - return err -} - -func (s *snapshotter) AddThread(e *event.Event) error { - pid, err := e.Params.GetPid() - if err != nil { - return err - } - threadCount.Add(1) - - s.mu.Lock() - defer s.mu.Unlock() - proc, ok := s.procs[pid] - if !ok { - return nil - } - - thread := pstypes.Thread{} - thread.Tid, _ = e.Params.GetTid() - thread.UstackBase = e.Params.TryGetAddress(params.UstackBase) - thread.UstackLimit = e.Params.TryGetAddress(params.UstackLimit) - thread.KstackBase = e.Params.TryGetAddress(params.KstackBase) - thread.KstackLimit = e.Params.TryGetAddress(params.KstackLimit) - thread.IOPrio, _ = e.Params.GetUint8(params.IOPrio) - thread.BasePrio, _ = e.Params.GetUint8(params.BasePrio) - thread.PagePrio, _ = e.Params.GetUint8(params.PagePrio) - thread.StartAddress = e.Params.TryGetAddress(params.StartAddress) - - proc.AddThread(thread) - - return nil -} - -func (s *snapshotter) AddModule(e *event.Event) error { - pid, err := e.Params.GetPid() - if err != nil { - return err - } - s.mu.Lock() - defer s.mu.Unlock() - - if pid == 0 && e.IsModuleRundown() { - // assume system process if pid is zero - pid = SystemPID - } - proc, ok := s.procs[pid] - if !ok { - return nil - } - - module := pstypes.Module{} - module.Size, _ = e.Params.GetUint64(params.ModuleSize) - module.Checksum, _ = e.Params.GetUint32(params.ModuleCheckSum) - module.TimedateStamp, _ = e.Params.GetUint32(params.ModuleTimeDateStamp) - module.Name = e.GetParamAsString(params.ModulePath) - module.BaseAddress = e.Params.TryGetAddress(params.ModuleBase) - module.DefaultBaseAddress = e.Params.TryGetAddress(params.ModuleDefaultBase) - - if e.IsLoadModuleInternal() { - proc.AddModule(module) - return nil - } - - moduleCount.Add(1) - - module.SignatureLevel, _ = e.Params.GetUint32(params.ModuleSignatureLevel) - module.SignatureType, _ = e.Params.GetUint32(params.ModuleSignatureType) - - if strings.EqualFold(proc.Name, filepath.Base(module.Name)) && len(proc.Exe) < len(module.Name) { - // if the module is loaded for the process executable, and - // we don't have the full executable path, override with - // the one from the Module path - proc.Exe = module.Name - } - - proc.AddModule(module) - - return nil -} - -func (s *snapshotter) RemoveThread(pid uint32, tid uint32) error { - s.mu.Lock() - defer s.mu.Unlock() - proc, ok := s.procs[pid] - if !ok { - return nil - } - proc.RemoveThread(tid) - threadCount.Add(-1) - return nil -} - -func (s *snapshotter) RemoveModule(pid uint32, addr va.Address) error { - s.mu.Lock() - defer s.mu.Unlock() - proc, ok := s.procs[pid] - if !ok { - return nil - } - proc.RemoveModule(addr) - moduleCount.Add(-1) - return nil -} - -func (s *snapshotter) FindModule(addr va.Address) (bool, *pstypes.Module) { - s.mu.RLock() - defer s.mu.RUnlock() - for _, proc := range s.procs { - for _, mod := range proc.Modules { - if mod.BaseAddress == addr { - return true, &mod - } - } - } - return false, nil -} - -func (s *snapshotter) FindAllModules() map[string]pstypes.Module { - s.mu.RLock() - defer s.mu.RUnlock() - mods := make(map[string]pstypes.Module) - for _, proc := range s.procs { - for _, mod := range proc.Modules { - if _, ok := mods[mod.Name]; ok { - continue - } - mods[mod.Name] = mod - } - } - return mods -} - -func (s *snapshotter) AddMmap(e *event.Event) error { - s.mu.Lock() - defer s.mu.Unlock() - proc, ok := s.procs[e.PID] - if !ok { - return nil - } - - mmapCount.Add(1) - - mmap := pstypes.Mmap{} - mmap.File = e.GetParamAsString(params.FilePath) - mmap.BaseAddress = e.Params.TryGetAddress(params.FileViewBase) - mmap.Size, _ = e.Params.GetUint64(params.FileViewSize) - mmap.Protection, _ = e.Params.GetUint32(params.MemProtect) - mmap.Type = e.GetParamAsString(params.FileViewSectionType) - - proc.AddMmap(mmap) - - return nil -} - -func (s *snapshotter) RemoveMmap(pid uint32, addr va.Address) error { - s.mu.Lock() - defer s.mu.Unlock() - proc, ok := s.procs[pid] - if !ok { - return nil - } - mmapCount.Add(-1) - proc.RemoveMmap(addr) - return nil -} - -func (s *snapshotter) Close() error { - s.quit <- struct{}{} - return nil -} - -func (s *snapshotter) newProcState(pid, ppid uint32, e *event.Event) (*pstypes.PS, error) { - if e.IsCreateProcessInternal() || e.IsProcessRundownInternal() { - proc := &pstypes.PS{ - PID: pid, - Ppid: ppid, - Exe: e.GetParamAsString(params.Exe), - Name: filepath.Base(e.GetParamAsString(params.Exe)), - TokenIntegrityLevel: e.GetParamAsString(params.ProcessTokenIntegrityLevel), - TokenElevationType: e.GetParamAsString(params.ProcessTokenElevationType), - IsTokenElevated: e.Params.TryGetBool(params.ProcessTokenIsElevated), - Threads: make(map[uint32]pstypes.Thread), - Modules: make([]pstypes.Module, 0), - Handles: make([]htypes.Handle, 0), - Mmaps: make([]pstypes.Mmap, 0), - } - - return proc, nil - } - - proc := pstypes.New( - pid, - ppid, - e.GetParamAsString(params.ProcessName), - e.GetParamAsString(params.Cmdline), - e.GetParamAsString(params.Exe), - e.Params.MustGetSID(), - e.Params.MustGetUint32(params.SessionID), - ) - - proc.Parent = s.procs[ppid] - proc.StartTime, _ = e.Params.GetTime(params.StartTime) - proc.IsWOW64 = (e.Params.MustGetUint32(params.ProcessFlags) & event.PsWOW64) != 0 - proc.IsPackaged = (e.Params.MustGetUint32(params.ProcessFlags) & event.PsPackaged) != 0 - proc.IsProtected = (e.Params.MustGetUint32(params.ProcessFlags) & event.PsProtected) != 0 - proc.IsCreatedFromSystemLogger = true - - if !s.capture { - if proc.Username != "" { - e.AppendParam(params.Username, params.UnicodeString, proc.Username) - } - if proc.Domain != "" { - e.AppendParam(params.Domain, params.UnicodeString, proc.Domain) - } - // retrieve process handles - var err error - proc.Handles, err = s.hsnap.FindHandles(pid) - if err != nil { - return proc, err - } - } - - // return early if we're reading from the capture file - if s.capture { - // reset username/domain from captured event parameters - proc.Domain = e.GetParamAsString(params.Domain) - proc.Username = e.GetParamAsString(params.Username) - return proc, nil - } - - // retrieve Portable Executable data - var err error - proc.PE, err = pe.ParseFileWithConfig(proc.Exe, s.config.PE) - if err != nil { - return proc, err - } - - // try to read the PEB (Process Environment Block) - // to access environment variables and the process - // current working directory - access := uint32(windows.PROCESS_QUERY_INFORMATION | windows.PROCESS_VM_READ) - process, err := windows.OpenProcess(access, false, pid) - if err != nil { - process, err = windows.OpenProcess(windows.PROCESS_QUERY_INFORMATION, false, pid) - if err != nil { - return proc, nil - } - } - //nolint:errcheck - defer windows.CloseHandle(process) - - // query token attributes if not enriched by internal event - if s.procs[pid] == nil { - var token windows.Token - err = windows.OpenProcessToken(process, windows.TOKEN_QUERY, &token) - if err != nil { - goto readPEB - } - defer token.Close() - - // get process token integrity level - tokenMandatoryLabel, err := sys.GetProcessTokenInformation[windows.Tokenmandatorylabel](token, windows.TokenIntegrityLevel) - if err != nil { - goto readPEB - } - - proc.TokenIntegrityLevel = sys.RidToString(tokenMandatoryLabel.Label.Sid) - proc.IsTokenElevated = token.IsElevated() - - e.AppendParam(params.ProcessTokenIntegrityLevel, params.AnsiString, proc.TokenIntegrityLevel) - e.AppendParam(params.ProcessTokenIsElevated, params.Bool, proc.IsTokenElevated) - } - -readPEB: - // read PEB (Process Environment Block) - peb, err := ReadPEB(process) - if err != nil { - pebReadErrors.Add(1) - return proc, err - } - proc.Envs = peb.GetEnvs() - proc.Cwd = peb.GetCurrentWorkingDirectory() - - return proc, nil -} - -func (s *snapshotter) Remove(e *event.Event) error { - s.mu.Lock() - defer s.mu.Unlock() - pid, err := e.Params.GetPid() - if err != nil { - return err - } - // remove process from primary map and - // move to dirty map. This is required - // to prevent dropping process state from - // events when TerminateProcess event is - // emitted before subsequent events - if proc := s.procs[pid]; proc != nil { - s.dmu.Lock() - defer s.dmu.Unlock() - s.dirty[pid] = proc - // schedule removal - remove := func(pid uint32) func() { - return func() { - s.dmu.Lock() - defer s.dmu.Unlock() - if ps, ok := s.dirty[pid]; ok { - delete(s.dirty, pid) - log.Debugf("dirty process removed: %s. Dirty procs: %d", ps.Name, len(s.dirty)) - } - } - } - time.AfterFunc(time.Second*5, remove(pid)) - } - delete(s.procs, pid) - processCount.Add(-1) - // reset parent if it died after spawning a process - for procID, proc := range s.procs { - if proc.Ppid == pid { - s.procs[procID].Parent = nil - } - } - return nil -} - -func (s *snapshotter) Put(proc *pstypes.PS) { - if proc != nil { - s.mu.Lock() - defer s.mu.Unlock() - s.procs[proc.PID] = proc - } -} - -func (s *snapshotter) FindAndPut(pid uint32) *pstypes.PS { - ok, proc := s.Find(pid) - if !ok { - s.Put(proc) - } - return proc -} - -func (s *snapshotter) Find(pid uint32) (bool, *pstypes.PS) { - s.mu.RLock() - defer s.mu.RUnlock() - ps, ok := s.procs[pid] - if ok { - return true, ps - } - if s.capture || pid == sys.InvalidProcessID { - return false, nil - } - - // check if the process is in dirty map - s.dmu.RLock() - defer s.dmu.RUnlock() - if ps := s.dirty[pid]; ps != nil { - return true, ps - } - - processLookupFailureCount.Add(strconv.Itoa(int(pid)), 1) - - proc := &pstypes.PS{ - PID: pid, - Ppid: sys.InvalidProcessID, - Threads: make(map[uint32]pstypes.Thread), - Modules: make([]pstypes.Module, 0), - Handles: make([]htypes.Handle, 0), - } - - getProcExecutable := func(process windows.Handle) (string, string) { - var size uint32 = windows.MAX_PATH - n := make([]uint16, size) - err := windows.QueryFullProcessImageName(process, 0, &n[0], &size) - if err != nil { - return "", "" - } - return windows.UTF16ToString(n), filepath.Base(windows.UTF16ToString(n)) - } - - access := uint32(windows.PROCESS_QUERY_INFORMATION | windows.PROCESS_VM_READ) - process, err := windows.OpenProcess(access, false, pid) - if err != nil { - // the access to protected / system process can't be achieved - // through `PROCESS_VM_READ` or `PROCESS_QUERY_INFORMATION` flags. - // Try to acquire the process handle again but with restricted access - // rights to be able to obtain other attributes such as the full process's - // Module executable path or process times - process, err = windows.OpenProcess(windows.PROCESS_QUERY_LIMITED_INFORMATION, false, pid) - if err != nil { - return false, nil - } - } - //nolint:errcheck - defer windows.CloseHandle(process) - - // get process executable full path and name - proc.Exe, proc.Name = getProcExecutable(process) - - // consult process parent id - info, err := sys.QueryInformationProcess[windows.PROCESS_BASIC_INFORMATION](process, windows.ProcessBasicInformation) - if err != nil { - return false, proc - } - proc.Ppid = uint32(info.InheritedFromUniqueProcessId) - - // retrieve Portable Executable data - proc.PE, err = pe.ParseFileWithConfig(proc.Exe, s.config.PE) - if err != nil { - return false, proc - } - - // get process times - var ( - ct windows.Filetime - xt windows.Filetime - kt windows.Filetime - ut windows.Filetime - ) - err = windows.GetProcessTimes(process, &ct, &xt, &kt, &ut) - if err != nil { - return false, proc - } - proc.StartTime = time.Unix(0, ct.Nanoseconds()) - - // get process creation attributes - var isWOW64 bool - if err := windows.IsWow64Process(process, &isWOW64); err == nil && isWOW64 { - proc.IsWOW64 = true - } - if isPackaged, err := sys.IsProcessPackaged(process); err == nil && isPackaged { - proc.IsPackaged = true - } - if prot, err := sys.QueryInformationProcess[sys.PsProtection](process, sys.ProcessProtectionInformation); err == nil && prot != nil { - proc.IsProtected = prot.IsProtected() - } - - // get process token attributes - var ( - token windows.Token - tokenUser *windows.Tokenuser - tokenMandatoryLabel *windows.Tokenmandatorylabel - ) - - err = windows.OpenProcessToken(process, windows.TOKEN_QUERY, &token) - if err != nil { - goto readPEB - } - defer token.Close() - tokenUser, err = token.GetTokenUser() - if err != nil { - goto readPEB - } - proc.SID = tokenUser.User.Sid.String() - proc.Username, proc.Domain, _, _ = tokenUser.User.Sid.LookupAccount("") - - // get process token integrity level - tokenMandatoryLabel, err = sys.GetProcessTokenInformation[windows.Tokenmandatorylabel](token, windows.TokenIntegrityLevel) - if err != nil { - goto readPEB - } - - proc.TokenIntegrityLevel = sys.RidToString(tokenMandatoryLabel.Label.Sid) - proc.IsTokenElevated = token.IsElevated() - - // retrieve process handles - proc.Handles, err = s.hsnap.FindHandles(pid) - if err != nil { - goto readPEB - } - -readPEB: - // read PEB (Process Environment Block) - peb, err := ReadPEB(process) - if err != nil { - pebReadErrors.Add(1) - return false, proc - } - proc.Envs = peb.GetEnvs() - proc.Cmdline = peb.GetCommandLine() - proc.SessionID = peb.GetSessionID() - proc.Cwd = peb.GetCurrentWorkingDirectory() - - return false, proc -} - -func (s *snapshotter) Size() uint32 { - s.mu.RLock() - defer s.mu.RUnlock() - return uint32(len(s.procs)) -} - -// gcDeadProcesses periodically scans the map of the snapshot's processes and removes -// any terminated processes from it. This guarantees that any leftovers are cleaned-up -// in case we miss process' terminate events. -func (s *snapshotter) gcDeadProcesses() { - tick := time.NewTicker(reapPeriod) - for { - select { - case <-tick.C: - s.mu.Lock() - ss := len(s.procs) - log.Debugf("scanning for dead processes on the snapshot of %d items", ss) - - for pid := range s.procs { - proc, err := windows.OpenProcess(windows.PROCESS_QUERY_LIMITED_INFORMATION, false, pid) - if err != nil { - continue - } - if !sys.IsProcessRunning(proc) { - delete(s.procs, pid) - } - _ = windows.CloseHandle(proc) - } - - if ss > len(s.procs) { - reaped := ss - len(s.procs) - reapedProcesses.Add(int64(reaped)) - log.Debugf("%d dead process(es) reaped", reaped) - } - s.mu.Unlock() - case <-s.quit: - tick.Stop() - } - } -} - -func (s *snapshotter) onHandleCreated(pid uint32, handle htypes.Handle) { - s.mu.RLock() - ps, ok := s.procs[pid] - s.mu.RUnlock() - if ok { - s.mu.Lock() - defer s.mu.Unlock() - ps.AddHandle(handle) - s.procs[pid] = ps - } -} - -func (s *snapshotter) onHandleDestroyed(pid uint32, rawHandle windows.Handle) { - s.mu.RLock() - ps, ok := s.procs[pid] - s.mu.RUnlock() - if ok { - s.mu.Lock() - defer s.mu.Unlock() - ps.RemoveHandle(rawHandle) - s.procs[pid] = ps - } +// Snapshotter is the interface that exposes a set of methods all process snapshotters have to satisfy. It stores the state +// of all running processes in the system including its threads, dynamically loaded libraries, handles/file descriptors +// and other metadata. +type Snapshotter interface { + // Write appends a new process state to the snapshotter. It takes as an input the inbound event to fetch + // the basic data, but also enriches the process' state with extra metadata such as process' env variables, PE + // metadata for Windows binaries and so on. + Write(*event.Event) error + // AddThread builds thread state from the event representation. + AddThread(*event.Event) error + // AddModule builds module state from the event representation. + AddModule(*event.Event) error + // RemoveThread removes the thread from the given process. + RemoveThread(pid uint32, tid uint32) error + // RemoveModule removes the module the given process. + RemoveModule(pid uint32, addr va.Address) error + // AddMmap adds a new memory mapping (data memory-mapped file, image, or pagefile) to this process state. + AddMmap(*event.Event) error + // RemoveMmap removes memory mapping at the given base address. + RemoveMmap(pid uint32, addr va.Address) error + // WriteFromCapture appends a new process state to the snapshotter from the captured event. + WriteFromCapture(evt *event.Event) error + // Remove deletes process's state from the snapshotter. + Remove(evt *event.Event) error + // Find attempts to retrieve process' state for the specified process identifier. Returns true + // if the process was find in the state. Otherwise, returns false and constructs a fresh process + // state by querying the OS via API functions. + Find(pid uint32) (bool, *pstypes.PS) + // FindModule traverses loaded modules of all processes in the snapshot and + // if there is module with the specified base address, it returns its metadata. + FindModule(addr va.Address) (bool, *pstypes.Module) + // FindAllModules finds all unique modules across the snapshotter state. + FindAllModules() map[string]pstypes.Module + // FindAndPut attempts to retrieve process' state for the specified process identifier. + // If the process is found, the snapshotter state is updated with the new process. + FindAndPut(pid uint32) *pstypes.PS + // Put inserts the process state into snapshotter. + Put(*pstypes.PS) + // Size returns the total number of process state items. + Size() uint32 + // Close closes process snapshotter and disposes all allocated resources. + Close() error } diff --git a/pkg/util/ntstatus/status_windows.go b/pkg/util/ntstatus/status.go similarity index 100% rename from pkg/util/ntstatus/status_windows.go rename to pkg/util/ntstatus/status.go diff --git a/pkg/util/rest/rest.go b/pkg/util/rest/rest.go index 507d35478..b2e48b90d 100644 --- a/pkg/util/rest/rest.go +++ b/pkg/util/rest/rest.go @@ -46,9 +46,9 @@ type Option func(o *opts) func WithTransport(addr string) Option { return func(o *opts) { o.addr = addr - if strings.HasPrefix(addr, `npipe:///`) { + if strings.HasPrefix(addr, `npipe:///`) || strings.HasPrefix(addr, `unix://`) { transport = &http.Transport{ - DialContext: api.DialPipe(addr), + DialContext: api.DialLocalTransport(addr), } } else { transport = &http.Transport{ @@ -104,6 +104,9 @@ func request(method string, options ...Option) ([]byte, error) { scheme := "http://" addr := strings.TrimPrefix(opts.addr, `npipe:///`) + if strings.HasPrefix(addr, "unix://") { + addr = "localhost" + } ctx, cancel := context.WithTimeout(context.Background(), time.Second*10) defer cancel() diff --git a/pkg/util/rest/rest_linux_test.go b/pkg/util/rest/rest_linux_test.go new file mode 100644 index 000000000..e0215cba7 --- /dev/null +++ b/pkg/util/rest/rest_linux_test.go @@ -0,0 +1,55 @@ +//go:build linux + +/* + * Copyright 2026 by Mostafa Moradian + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package rest + +import ( + "net" + "net/http" + "net/http/httptest" + "path/filepath" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestGetUnixSocket(t *testing.T) { + path := filepath.Join(t.TempDir(), "fibratus.sock") + listener, err := net.Listen("unix", path) + require.NoError(t, err) + + mux := http.NewServeMux() + mux.HandleFunc("/config", func(w http.ResponseWriter, _ *http.Request) { + if _, err := w.Write([]byte("test")); err != nil { + t.Fatal(err) + } + }) + + srv := httptest.NewUnstartedServer(mux) + srv.Listener = listener + srv.Start() + defer srv.Close() + + resp, err := Get(WithURI("config"), WithTransport("unix://"+path)) + require.NoError(t, err) + require.NotNil(t, resp) + assert.Equal(t, "test", string(resp)) +} diff --git a/pkg/util/rest/rest_test.go b/pkg/util/rest/rest_test.go index 396cce923..491880430 100644 --- a/pkg/util/rest/rest_test.go +++ b/pkg/util/rest/rest_test.go @@ -20,12 +20,10 @@ package rest import ( "fmt" - "github.com/rabbitstack/fibratus/pkg/api" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "net/http" "net/http/httptest" - "os/user" "strings" "testing" ) @@ -47,33 +45,6 @@ func TestGet(t *testing.T) { assert.Equal(t, "test", string(resp)) } -func TestGetPipe(t *testing.T) { - usr, err := user.Current() - require.NoError(t, err) - descriptor := "D:P(A;;GA;;;" + usr.Uid + ")" - listener, err := api.MakePipeListener(`npipe:///fibratus`, descriptor) - require.NoError(t, err) - - mux := http.NewServeMux() - - mux.HandleFunc("/config", func(w http.ResponseWriter, r *http.Request) { - if _, err := w.Write([]byte("test")); err != nil { - t.Fatal(err) - } - }) - - srv := httptest.NewUnstartedServer(mux) - srv.Listener = listener - - srv.Start() - defer srv.Close() - - resp, err := Get(WithURI("config"), WithTransport(`npipe:///fibratus`)) - require.NoError(t, err) - require.NotNil(t, resp) - assert.Equal(t, "test", string(resp)) -} - func port(s string) string { i := strings.LastIndex(s, ":") if i == 0 { diff --git a/pkg/util/rest/rest_windows_test.go b/pkg/util/rest/rest_windows_test.go new file mode 100644 index 000000000..d7d4a0182 --- /dev/null +++ b/pkg/util/rest/rest_windows_test.go @@ -0,0 +1,57 @@ +//go:build windows + +/* + * Copyright 2019-2020 by Nedim Sabic Sabic + * https://www.fibratus.io + * All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package rest + +import ( + "net/http" + "net/http/httptest" + "os/user" + "testing" + + "github.com/rabbitstack/fibratus/pkg/api" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestGetPipe(t *testing.T) { + usr, err := user.Current() + require.NoError(t, err) + descriptor := "D:P(A;;GA;;;" + usr.Uid + ")" + listener, err := api.MakePipeListener(`npipe:///fibratus`, descriptor) + require.NoError(t, err) + + mux := http.NewServeMux() + mux.HandleFunc("/config", func(w http.ResponseWriter, _ *http.Request) { + if _, err := w.Write([]byte("test")); err != nil { + t.Fatal(err) + } + }) + + srv := httptest.NewUnstartedServer(mux) + srv.Listener = listener + srv.Start() + defer srv.Close() + + resp, err := Get(WithURI("config"), WithTransport(`npipe:///fibratus`)) + require.NoError(t, err) + require.NotNil(t, resp) + assert.Equal(t, "test", string(resp)) +} From ea105896a1ea66df54a43614a29a24edeb6eb39b Mon Sep 17 00:00:00 2001 From: Mostafa Moradian Date: Wed, 12 Aug 2026 15:01:56 +0200 Subject: [PATCH 28/28] refactor(config): enforce Linux-native event settings Keep process events mandatory, reuse the established file-I/O setting, and remove deprecated kevt fields from Linux. Restore documentation lost while splitting shared and Windows-specific configuration and parameter catalogs. --- pkg/config/alertsender_linux.go | 6 +- pkg/config/config.go | 50 +++++-- pkg/config/config.schema.json | 6 - pkg/config/eventsource_linux.go | 28 ++-- pkg/config/eventsource_linux_test.go | 7 +- pkg/event/params/names_windows.go | 201 ++++++++++++++++++--------- pkg/event/params/param_types.go | 83 +++++++---- pkg/event/params/types_windows.go | 25 ++-- pkg/filter/fields/defs_linux.go | 2 - pkg/filter/fields/defs_linux_test.go | 2 + 10 files changed, 262 insertions(+), 148 deletions(-) diff --git a/pkg/config/alertsender_linux.go b/pkg/config/alertsender_linux.go index 1818cc7f1..74c780c5d 100644 --- a/pkg/config/alertsender_linux.go +++ b/pkg/config/alertsender_linux.go @@ -22,10 +22,6 @@ package config import "github.com/rabbitstack/fibratus/pkg/alertsender" -func (c *Config) loadPlatformAlertSender(typ string, config interface{}, configs *[]alertsender.Config) error { - // Platform-specific Linux alert senders can be loaded here. - _ = typ - _ = config - _ = configs +func (c *Config) loadPlatformAlertSender(_ string, _ interface{}, _ *[]alertsender.Config) error { return nil } diff --git a/pkg/config/config.go b/pkg/config/config.go index 534f97802..a5e135e12 100644 --- a/pkg/config/config.go +++ b/pkg/config/config.go @@ -60,17 +60,28 @@ const ( type Config struct { platformConfig - EventSource EventSourceConfig `json:"eventsource" yaml:"eventsource"` - Filament FilamentConfig `json:"filament" yaml:"filament"` - API APIConfig `json:"api" yaml:"api"` - Output outputs.Config - Aggregator aggregator.Config `json:"aggregator" yaml:"aggregator"` - Log log.Config `json:"logging" yaml:"logging"` + // EventSource stores options for fine-tuning the event source. + EventSource EventSourceConfig `json:"eventsource" yaml:"eventsource"` + // Filament contains filament settings. + Filament FilamentConfig `json:"filament" yaml:"filament"` + // API stores global HTTP API preferences. + API APIConfig `json:"api" yaml:"api"` + // Output stores the currently active output configuration. + Output outputs.Config + // Aggregator stores event aggregator configuration. + Aggregator aggregator.Config `json:"aggregator" yaml:"aggregator"` + // Log contains logging configuration. + Log log.Config `json:"logging" yaml:"logging"` + // Transformers stores transformer configurations. Transformers []transformers.Config + // Alertsenders stores alert sender configurations. Alertsenders []alertsender.Config - Filters *Filters `json:"filters" yaml:"filters"` - ForwardMode bool `json:"forward" yaml:"forward"` - CapFile string + // Filters contains filter and rule definitions. + Filters *Filters `json:"filters" yaml:"filters"` + // ForwardMode designates whether event forwarding mode is engaged. + ForwardMode bool `json:"forward" yaml:"forward"` + // CapFile is the path to the capture file. + CapFile string flags *pflag.FlagSet viper *viper.Viper @@ -90,11 +101,22 @@ type Options struct { // Option configures the command-specific configuration surface. type Option func(*Options) -func WithCapture() Option { return func(o *Options) { o.capture = true } } -func WithReplay() Option { return func(o *Options) { o.replay = true } } -func WithRun() Option { return func(o *Options) { o.run = true } } -func WithList() Option { return func(o *Options) { o.list = true } } -func WithStats() Option { return func(o *Options) { o.stats = true } } +// WithCapture determines whether the capture command is executed. +func WithCapture() Option { return func(o *Options) { o.capture = true } } + +// WithReplay determines whether the replay command is executed. +func WithReplay() Option { return func(o *Options) { o.replay = true } } + +// WithRun determines whether the run command is executed. +func WithRun() Option { return func(o *Options) { o.run = true } } + +// WithList determines whether the list command is executed. +func WithList() Option { return func(o *Options) { o.list = true } } + +// WithStats determines whether the stats command is executed. +func WithStats() Option { return func(o *Options) { o.stats = true } } + +// WithValidate determines whether the validate command is executed. func WithValidate() Option { return func(o *Options) { o.validate = true } } // NewWithOpts builds a new configuration store from files, environment variables, and flags. diff --git a/pkg/config/config.schema.json b/pkg/config/config.schema.json index a6ce003a9..f2a381d55 100644 --- a/pkg/config/config.schema.json +++ b/pkg/config/config.schema.json @@ -335,12 +335,6 @@ "eventsource": { "type": "object", "properties": { - "enable-process": { - "type": "boolean" - }, - "enable-file": { - "type": "boolean" - }, "enable-thread": { "type": "boolean" }, diff --git a/pkg/config/eventsource_linux.go b/pkg/config/eventsource_linux.go index 7de7ba2c1..77d02f209 100644 --- a/pkg/config/eventsource_linux.go +++ b/pkg/config/eventsource_linux.go @@ -27,28 +27,25 @@ import ( ) const ( - enableProcessEvents = "eventsource.enable-process" - enableFileEvents = "eventsource.enable-file" - enableNetEvents = "eventsource.enable-net" - enableMemEvents = "eventsource.enable-mem" - excludedEvents = "eventsource.blacklist.events" - excludedImages = "eventsource.blacklist.images" + enableFileIOEvents = "eventsource.enable-fileio" + enableNetEvents = "eventsource.enable-net" + enableMemEvents = "eventsource.enable-mem" + excludedEvents = "eventsource.blacklist.events" + excludedImages = "eventsource.blacklist.images" ) type EventSourceConfig struct { eventSourceConfig - ExcludedEvents []string `json:"blacklist.events" yaml:"blacklist.events"` - ExcludedImages []string `json:"blacklist.images" yaml:"blacklist.images"` - EnableProcessEvents bool `json:"enable-process" yaml:"enable-process"` - EnableFileIOEvents bool `json:"enable-file" yaml:"enable-file"` - EnableNetEvents bool `json:"enable-net" yaml:"enable-net"` - EnableMemEvents bool `json:"enable-mem" yaml:"enable-mem"` + ExcludedEvents []string `json:"blacklist.events" yaml:"blacklist.events"` + ExcludedImages []string `json:"blacklist.images" yaml:"blacklist.images"` + EnableFileIOEvents bool `json:"enable-fileio" yaml:"enable-fileio"` + EnableNetEvents bool `json:"enable-net" yaml:"enable-net"` + EnableMemEvents bool `json:"enable-mem" yaml:"enable-mem"` } func (c *EventSourceConfig) AddFlags(flags *pflag.FlagSet) { - flags.Bool(enableProcessEvents, true, "Determines whether process events are collected") - flags.Bool(enableFileEvents, true, "Determines whether file events are collected") + flags.Bool(enableFileIOEvents, true, "Determines whether file events are collected") flags.Bool(enableNetEvents, true, "Determines whether network events are collected") flags.Bool(enableMemEvents, true, "Determines whether memory events are collected") flags.StringSlice(excludedEvents, nil, "A list of event names to drop") @@ -56,8 +53,7 @@ func (c *EventSourceConfig) AddFlags(flags *pflag.FlagSet) { } func (c *EventSourceConfig) initFromViper(v *viper.Viper) { - c.EnableProcessEvents = v.GetBool(enableProcessEvents) - c.EnableFileIOEvents = v.GetBool(enableFileEvents) + c.EnableFileIOEvents = v.GetBool(enableFileIOEvents) c.EnableNetEvents = v.GetBool(enableNetEvents) c.EnableMemEvents = v.GetBool(enableMemEvents) c.ExcludedEvents = v.GetStringSlice(excludedEvents) diff --git a/pkg/config/eventsource_linux_test.go b/pkg/config/eventsource_linux_test.go index 140fdc91a..555e6d0bd 100644 --- a/pkg/config/eventsource_linux_test.go +++ b/pkg/config/eventsource_linux_test.go @@ -33,14 +33,14 @@ import ( func TestEventSourceConfigLinux(t *testing.T) { c := NewWithOpts(WithRun()) require.NoError(t, c.flags.Parse([]string{ - "--eventsource.enable-process=false", + "--eventsource.enable-fileio=false", "--eventsource.blacklist.events=execve", "--eventsource.blacklist.images=systemd", })) require.NoError(t, c.viper.BindPFlags(c.flags)) require.NoError(t, c.Init()) - require.False(t, c.EventSource.EnableProcessEvents) + require.False(t, c.EventSource.EnableFileIOEvents) require.True(t, c.EventSource.ExcludeEvent(event.Execve.ID())) require.True(t, c.EventSource.ExcludeImage(&pstypes.PS{Name: "systemd"})) for _, typ := range event.All() { @@ -51,8 +51,7 @@ func TestEventSourceConfigLinux(t *testing.T) { func TestValidateLinuxEventSource(t *testing.T) { file := filepath.Join(t.TempDir(), "fibratus.yml") require.NoError(t, os.WriteFile(file, []byte(`eventsource: - enable-process: true - enable-file: true + enable-fileio: true blacklist: events: - execve diff --git a/pkg/event/params/names_windows.go b/pkg/event/params/names_windows.go index a457c1e10..a05e33f26 100644 --- a/pkg/event/params/names_windows.go +++ b/pkg/event/params/names_windows.go @@ -19,73 +19,142 @@ package params const ( - NTStatus = "status" - ProcessObject = "kproc" - Callstack = "callstack" - CallstackTimestamp = "callstack_timestamp" - ProcessRealParentID = "real_ppid" - UserSID = "sid" - Domain = "domain" - DTB = "directory_table_base" + // NTStatus identifies the NTSTATUS value. + NTStatus = "status" + // ProcessObject represents the address of the process object in the kernel. + ProcessObject = "kproc" + // Callstack represents the thread call stack. + Callstack = "callstack" + // CallstackTimestamp identifies the call stack timestamp. + CallstackTimestamp = "callstack_timestamp" + // ProcessRealParentID represents the real parent process identifier. + ProcessRealParentID = "real_ppid" + // UserSID is the security identifier associated with the process token. + UserSID = "sid" + // Domain represents the domain under which the event was generated. + Domain = "domain" + // DTB denotes the address of the process directory table. + DTB = "directory_table_base" + // ProcessTokenIntegrityLevel denotes the process integrity level. ProcessTokenIntegrityLevel = "token_integrity_level" - ProcessTokenElevationType = "token_elevation_type" - ProcessTokenIsElevated = "token_is_elevated" - DesiredAccess = "desired_access" - BasePrio = "base_prio" - IOPrio = "io_prio" - PagePrio = "page_prio" - KstackBase = "kstack" - KstackLimit = "kstack_limit" - UstackBase = "ustack" - UstackLimit = "ustack_limit" - StartAddress = "start_address" - StartAddressSymbol = "start_address_symbol" - StartAddressModule = "start_address_module" - TEB = "teb" - FileCreateOptions = "create_options" - FileOperation = "create_disposition" - FileShareMask = "share_mask" - FileAttributes = "attributes" - FileInfoClass = "class" - FileIrpPtr = "irp" - FileIsDLL = "is_dll" - FileIsDriver = "is_driver" - FileIsDotnet = "is_dotnet" - RegKeyHandle = "key_handle" - RegKCB = "kcb" - RegPath = "key_path" - RegValue = "value" - RegValueType = "value_type" - RegData = "data" - ModuleCheckSum = "checksum" - ModuleTimeDateStamp = "timedate_stamp" - ModuleDefaultBase = "default_address" - ModuleSignatureLevel = "signature_level" - ModuleSignatureType = "signature_type" - ModuleCertSubject = "cert_subject" - ModuleCertIssuer = "cert_issuer" - ModuleCertSerial = "cert_serial" - ModuleCertNotBefore = "cert_not_before" - ModuleCertNotAfter = "cert_not_after" - HandleID = "handle_id" - HandleSourceID = "handle_source_id" - HandleObject = "handle_object" - HandleObjectName = "handle_name" - HandleObjectTypeID = "type_id" - ThreadpoolPoolID = "pool_id" - ThreadpoolTaskID = "task_id" - ThreadpoolCallback = "callback" - ThreadpoolCallbackSymbol = "callback_symbol" - ThreadpoolCallbackModule = "callback_module" - ThreadpoolContext = "context" - ThreadpoolContextRip = "context_rip" + // ProcessTokenElevationType designates the process token elevation type. + ProcessTokenElevationType = "token_elevation_type" + // ProcessTokenIsElevated designates whether the process token is elevated. + ProcessTokenIsElevated = "token_is_elevated" + // DesiredAccess denotes the access rights for a kernel object. + DesiredAccess = "desired_access" + // BasePrio is the thread base priority assigned by the scheduler. + BasePrio = "base_prio" + // IOPrio indicates the thread I/O priority. + IOPrio = "io_prio" + // PagePrio denotes the page priority. + PagePrio = "page_prio" + // KstackBase is the start address of the kernel-space stack. + KstackBase = "kstack" + // KstackLimit is the end address of the kernel-space stack. + KstackLimit = "kstack_limit" + // UstackBase is the start address of the user-space stack. + UstackBase = "ustack" + // UstackLimit is the end address of the user-space stack. + UstackLimit = "ustack_limit" + // StartAddress is the thread start address. + StartAddress = "start_address" + // StartAddressSymbol is the symbol associated with the thread start address. + StartAddressSymbol = "start_address_symbol" + // StartAddressModule is the module containing the thread start address. + StartAddressModule = "start_address_module" + // TEB is the address of the Thread Environment Block. + TEB = "teb" + // FileCreateOptions represents options passed to NtCreateFile. + FileCreateOptions = "create_options" + // FileOperation represents the file create disposition. + FileOperation = "create_disposition" + // FileShareMask represents the file share access mask. + FileShareMask = "share_mask" + // FileAttributes represents file attribute values. + FileAttributes = "attributes" + // FileInfoClass represents the file information class. + FileInfoClass = "class" + // FileIrpPtr represents the I/O request packet identifier. + FileIrpPtr = "irp" + // FileIsDLL indicates whether the file is a DLL. + FileIsDLL = "is_dll" + // FileIsDriver indicates whether the file is a driver. + FileIsDriver = "is_driver" + // FileIsDotnet indicates whether the file is a .NET assembly. + FileIsDotnet = "is_dotnet" + // RegKeyHandle identifies the registry key handle. + RegKeyHandle = "key_handle" + // RegKCB identifies the registry key control block. + RegKCB = "kcb" + // RegPath represents the fully qualified registry key path. + RegPath = "key_path" + // RegValue identifies the registry value. + RegValue = "value" + // RegValueType identifies the registry value type. + RegValueType = "value_type" + // RegData stores the captured registry data. + RegData = "data" + // ModuleCheckSum is the module checksum. + ModuleCheckSum = "checksum" + // ModuleTimeDateStamp is the module timestamp. + ModuleTimeDateStamp = "timedate_stamp" + // ModuleDefaultBase is the module's default base address. + ModuleDefaultBase = "default_address" + // ModuleSignatureLevel is the loaded module signature level. + ModuleSignatureLevel = "signature_level" + // ModuleSignatureType is the loaded module signature type. + ModuleSignatureType = "signature_type" + // ModuleCertSubject is the module certificate subject. + ModuleCertSubject = "cert_subject" + // ModuleCertIssuer is the module certificate issuer. + ModuleCertIssuer = "cert_issuer" + // ModuleCertSerial is the module certificate serial number. + ModuleCertSerial = "cert_serial" + // ModuleCertNotBefore is the beginning of the module certificate validity period. + ModuleCertNotBefore = "cert_not_before" + // ModuleCertNotAfter is the end of the module certificate validity period. + ModuleCertNotAfter = "cert_not_after" + // HandleID identifies the handle. + HandleID = "handle_id" + // HandleSourceID identifies the source handle. + HandleSourceID = "handle_source_id" + // HandleObject identifies the kernel object backing the handle. + HandleObject = "handle_object" + // HandleObjectName is the handle object name. + HandleObjectName = "handle_name" + // HandleObjectTypeID is the handle object type identifier. + HandleObjectTypeID = "type_id" + // ThreadpoolPoolID identifies the thread pool. + ThreadpoolPoolID = "pool_id" + // ThreadpoolTaskID identifies the thread pool task. + ThreadpoolTaskID = "task_id" + // ThreadpoolCallback is the thread pool callback address. + ThreadpoolCallback = "callback" + // ThreadpoolCallbackSymbol is the thread pool callback symbol. + ThreadpoolCallbackSymbol = "callback_symbol" + // ThreadpoolCallbackModule is the module containing the callback. + ThreadpoolCallbackModule = "callback_module" + // ThreadpoolContext is the thread pool callback context. + ThreadpoolContext = "context" + // ThreadpoolContextRip is the instruction pointer in the callback context. + ThreadpoolContextRip = "context_rip" + // ThreadpoolContextRipSymbol is the symbol for the context instruction pointer. ThreadpoolContextRipSymbol = "context_rip_symbol" + // ThreadpoolContextRipModule is the module containing the context instruction pointer. ThreadpoolContextRipModule = "context_rip_module" - ThreadpoolSubprocessTag = "subprocess_tag" - ThreadpoolTimerDuetime = "duetime" - ThreadpoolTimerSubqueue = "subqueue" - ThreadpoolTimer = "timer" - ThreadpoolTimerPeriod = "period" - ThreadpoolTimerWindow = "window" - ThreadpoolTimerAbsolute = "absolute" + // ThreadpoolSubprocessTag is the thread pool subprocess tag. + ThreadpoolSubprocessTag = "subprocess_tag" + // ThreadpoolTimerDuetime is the timer due time. + ThreadpoolTimerDuetime = "duetime" + // ThreadpoolTimerSubqueue is the timer subqueue. + ThreadpoolTimerSubqueue = "subqueue" + // ThreadpoolTimer identifies the timer. + ThreadpoolTimer = "timer" + // ThreadpoolTimerPeriod is the timer period. + ThreadpoolTimerPeriod = "period" + // ThreadpoolTimerWindow is the timer window. + ThreadpoolTimerWindow = "window" + // ThreadpoolTimerAbsolute indicates whether the timer due time is absolute. + ThreadpoolTimerAbsolute = "absolute" ) diff --git a/pkg/event/params/param_types.go b/pkg/event/params/param_types.go index 094ff92f2..c62ee303e 100644 --- a/pkg/event/params/param_types.go +++ b/pkg/event/params/param_types.go @@ -22,34 +22,63 @@ package params type Type uint16 const ( - Null Type = 0 - Int8 Type = 3 - Uint8 Type = 4 - Int16 Type = 5 - Uint16 Type = 6 - Int32 Type = 7 - Uint32 Type = 8 - Int64 Type = 9 - Uint64 Type = 10 - Float Type = 11 - Double Type = 12 - Bool Type = 13 - Binary Type = 14 - PID Type = 18 - TID Type = 19 - Port Type = 21 - IP Type = 22 - IPv4 Type = 23 - IPv6 Type = 24 - Time Type = 25 - Slice Type = 26 - Enum Type = 27 - Map Type = 28 - Object Type = 29 - Path Type = 31 - Status Type = 32 - Flags Type = 34 + // Null is a null parameter type. + Null Type = 0 + // Int8 is a signed 8-bit integer. + Int8 Type = 3 + // Uint8 is an unsigned 8-bit integer. + Uint8 Type = 4 + // Int16 is a signed 16-bit integer. + Int16 Type = 5 + // Uint16 is an unsigned 16-bit integer. + Uint16 Type = 6 + // Int32 is a signed 32-bit integer. + Int32 Type = 7 + // Uint32 is an unsigned 32-bit integer. + Uint32 Type = 8 + // Int64 is a signed 64-bit integer. + Int64 Type = 9 + // Uint64 is an unsigned 64-bit integer. + Uint64 Type = 10 + // Float is an IEEE 4-byte floating-point number. + Float Type = 11 + // Double is an IEEE 8-byte floating-point number. + Double Type = 12 + // Bool is a boolean value. + Bool Type = 13 + // Binary is variable-sized binary data. + Binary Type = 14 + // PID is a process identifier. + PID Type = 18 + // TID is a thread identifier. + TID Type = 19 + // Port is an endpoint port number. + Port Type = 21 + // IP is an IP address. + IP Type = 22 + // IPv4 is an IPv4 address. + IPv4 Type = 23 + // IPv6 is an IPv6 address. + IPv6 Type = 24 + // Time is a timestamp. + Time Type = 25 + // Slice is a collection of items. + Slice Type = 26 + // Enum is an enumeration. + Enum Type = 27 + // Map is a map of values. + Map Type = 28 + // Object is a generic object. + Object Type = 29 + // Path is a normalized filesystem path. + Path Type = 31 + // Status is a system error code. + Status Type = 32 + // Flags is a bitmask. + Flags Type = 34 + // Flags64 is a 64-bit bitmask. Flags64 Type = 35 + // Address is a memory address. Address Type = 36 ) diff --git a/pkg/event/params/types_windows.go b/pkg/event/params/types_windows.go index 5a64fba36..a342c0b85 100644 --- a/pkg/event/params/types_windows.go +++ b/pkg/event/params/types_windows.go @@ -19,15 +19,24 @@ package params const ( + // UnicodeString is a UTF-16LE string. UnicodeString Type = 1 - AnsiString Type = 2 - GUID Type = 15 - Pointer Type = 16 - SID Type = 17 - WbemSID Type = 20 - DOSPath Type = 30 - Key Type = 33 - HandleType Type = 37 + // AnsiString is an 8-bit character string. + AnsiString Type = 2 + // GUID is a globally unique identifier. + GUID Type = 15 + // Pointer is an architecture-sized pointer value. + Pointer Type = 16 + // SID is a Windows security identifier. + SID Type = 17 + // WbemSID is a Web-Based Enterprise Management security identifier. + WbemSID Type = 20 + // DOSPath is a filesystem path in DOS device notation. + DOSPath Type = 30 + // Key is a registry key. + Key Type = 33 + // HandleType is a Windows handle type. + HandleType Type = 37 ) func platformTypeString(t Type) string { diff --git a/pkg/filter/fields/defs_linux.go b/pkg/filter/fields/defs_linux.go index 717dd8ffa..f0daa6b47 100644 --- a/pkg/filter/fields/defs_linux.go +++ b/pkg/filter/fields/defs_linux.go @@ -28,8 +28,6 @@ func platformAnsiString() params.Type { return params.String } var fields = platformFields(map[Field]FieldInfo{ EvtPID: {EvtPID, "process identifier generating the event", params.Uint64, []string{"evt.pid = 6"}, nil, nil}, EvtTID: {EvtTID, "thread identifier generating the event", params.Uint64, []string{"evt.tid = 1024"}, nil, nil}, - KevtPID: {KevtPID, "process identifier generating the event", params.Uint64, []string{"kevt.pid = 6"}, &Deprecation{Since: "3.0.0", Fields: []Field{EvtPID}}, nil}, - KevtTID: {KevtTID, "thread identifier generating the event", params.Uint64, []string{"kevt.tid = 1024"}, &Deprecation{Since: "3.0.0", Fields: []Field{EvtTID}}, nil}, PsPid: {PsPid, "process identifier", params.Uint64, []string{"ps.pid = 1024"}, nil, nil}, PsPpid: {PsPpid, "parent process identifier", params.Uint64, []string{"ps.ppid = 45"}, nil, nil}, PsParentPid: {PsParentPid, "parent process id", params.Uint64, []string{"ps.parent.pid = 4"}, nil, nil}, diff --git a/pkg/filter/fields/defs_linux_test.go b/pkg/filter/fields/defs_linux_test.go index 22eeaf939..381e3ac5b 100644 --- a/pkg/filter/fields/defs_linux_test.go +++ b/pkg/filter/fields/defs_linux_test.go @@ -36,6 +36,8 @@ func TestLinuxFields(t *testing.T) { require.Equal(t, params.Uint64, EvtPID.Type()) require.Equal(t, params.Uint64, EvtTID.Type()) require.Equal(t, params.Uint64, PsPid.Type()) + require.False(t, IsField(string(KevtPID))) + require.False(t, IsField(string(KevtTID))) require.False(t, IsField(string(PsComm))) require.False(t, IsField(string(RegistryPath))) require.False(t, IsField(string(PeEntrypoint)))