diff --git a/.github/workflows/linux-port.yml b/.github/workflows/linux-port.yml new file mode 100644 index 000000000..91061f369 --- /dev/null +++ b/.github/workflows/linux-port.yml @@ -0,0 +1,72 @@ +name: linux-port + +on: + pull_request: + branches: + - linux-port + workflow_dispatch: + +concurrency: + group: linux-port-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +env: + GO_VERSION: 1.26.x + GOLANGCI_LINT_VERSION: v2.9.0 + CLANG_VERSION: 18 + +jobs: + ebpf: + runs-on: ubuntu-latest + steps: + - name: Validate PR title + if: github.event_name == 'pull_request' + uses: amannn/action-semantic-pull-request@v5 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + - name: Checkout + uses: actions/checkout@v4 + - name: Install Go + uses: actions/setup-go@v5 + with: + go-version: ${{ env.GO_VERSION }} + # Deliberately before clang is installed: a checkout must build from the + # committed objects alone. + - name: Build without generation tools + run: make + - name: Install clang + run: | + sudo apt-get update + sudo apt-get install -y clang-${{ env.CLANG_VERSION }} llvm-${{ env.CLANG_VERSION }} + clang-${{ env.CLANG_VERSION }} --version + # The versioned packages ship no unversioned symlinks, so name both tools. + - name: Check generation drift + run: make ebpf-drift CLANG=clang-${{ env.CLANG_VERSION }} LLVM_STRIP=llvm-strip-${{ env.CLANG_VERSION }} + - name: Install golangci-lint + run: | + curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin ${{ env.GOLANGCI_LINT_VERSION }} + - name: Lint + run: | + export PATH=$(go env GOPATH)/bin:$PATH + make lint + - name: Unit tests + run: make test + - name: Race tests + run: make test-race + - name: Validate rules + run: | + ./cmd/fibratus/fibratus rules validate \ + --filters.rules.from-paths="rules/linux/*.yml" \ + --filters.macros.from-paths="rules/linux/macros/*.yml" + # Fails, rather than skips, when the runner cannot host the backend, so a + # green integration run always means programs actually loaded. + - name: Probe eBPF prerequisites + run: sudo -E env "PATH=$PATH" go test -tags ebpf_integration -count=1 -run TestPrerequisitesAreMet -v ./internal/ebpf + - name: Privileged process source + run: sudo -E env "PATH=$PATH" make test-integration + - name: Package + run: make pkg + - uses: actions/upload-artifact@v4 + with: + name: fibratus-linux-packages + path: build/pkg/* diff --git a/.gitignore b/.gitignore index 02ca2865e..86a383098 100644 --- a/.gitignore +++ b/.gitignore @@ -1,15 +1,25 @@ +# Binaries cmd/fibratus/fibratus.exe cmd/fibratus/fibratus.syso - +cmd/fibratus/fibratus cmd/systray/fibratus-systray.exe cmd/systray/fibratus-systray.syso +# Resource message table pkg/util/eventlog/mc/* !pkg/util/eventlog/mc/gen.go +# Windows MSI package build/msi/fibratus-* build/msi/*.wixpdb build/msi/*.msi +# IDE .idea +.vscode + +# Python bytecode cache filaments/__pycache__ + +# Linux packages +build/pkg/ diff --git a/.golangci.yml b/.golangci.yml index abc35b26c..a571fc4f5 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -1,8 +1,8 @@ version: "2" -run: - build-tags: - - cap - - filament +# run: +# build-tags: +# - cap +# - filament linters: default: none @@ -43,7 +43,7 @@ linters: path: pkg/util/ports/iana_ports.go - linters: - goconst - path: pkg/event/flags.go + path: pkg/event/flags_windows.go - linters: - goconst path: pkg/filter/ql/functions/(.+)\.go @@ -56,6 +56,9 @@ linters: - linters: - goconst path: pkg/filter/fields/fields_windows.go + - linters: + - goconst + path: pkg/filter/fields/defs_windows.go - linters: - goconst path: cmd/fibratus/app/list/list.go diff --git a/Makefile b/Makefile new file mode 100644 index 000000000..e93b372a0 --- /dev/null +++ b/Makefile @@ -0,0 +1,155 @@ +.DEFAULT_GOAL := build + +SHELL := /bin/bash +.SHELLFLAGS := -euo pipefail -c + +BPF2GO_VERSION := v0.20.0 +GOLANGCI_LINT_VERSION := v2.9.0 +NFPM_VERSION := v2.43.0 + +# The committed objects are byte-compared in CI, and clang encodes its version +# into BTF, so generating with a different major produces a spurious diff. +CLANG_VERSION := 18 + +# The generated objects target x86-64 and the runtime refuses other +# architectures, so building the binary pins the same one. +TARGET_ARCH ?= amd64 + +# Specifies a list of build flags +TAGS ?= + +BPF_DIR := internal/ebpf +BPF_OUT := $(BPF_DIR)/bpf + +CLANG ?= clang +LLVM_STRIP ?= llvm-strip +GO ?= go +GOFMT ?= gofmt +BPF2GO ?= go run github.com/cilium/ebpf/cmd/bpf2go@$(BPF2GO_VERSION) + +BPF_FLAGS := \ + -go-package bpf \ + -output-dir $(BPF_OUT) \ + -cc $(CLANG) \ + -strip $(LLVM_STRIP) \ + -target bpfel,bpfeb \ + -tags linux + +# Production headers first; spike/c is only the vmlinux.h fallback. +BPF_CFLAGS := \ + -I./$(BPF_DIR)/c \ + -I./$(BPF_DIR)/c/common \ + -I./$(BPF_DIR)/spike/c \ + -O2 \ + -g \ + -D__TARGET_ARCH_x86 + +# Find all eBPF sources. +BPF_SOURCES := $(wildcard $(BPF_DIR)/c/*.bpf.c) +BPF_NAMES := $(patsubst $(BPF_DIR)/c/%.bpf.c,%,$(BPF_SOURCES)) +BPF_TARGETS := $(foreach name,$(BPF_NAMES), \ + $(BPF_OUT)/$(name)_bpfel.go \ + $(BPF_OUT)/$(name)_bpfeb.go) + +titlecase = $(shell printf '%s' '$(1)' | awk '{print toupper(substr($$0,1,1)) substr($$0,2)}') + +.PHONY: ebpf +ebpf: check-clang $(BPF_TARGETS) +$(BPF_OUT)/%_bpfel.go $(BPF_OUT)/%_bpfeb.go &: $(BPF_DIR)/c/%.bpf.c + $(BPF2GO) $(BPF_FLAGS) -output-stem $* $(call titlecase,$*) $(BPF_DIR)/c/$*.bpf.c -- $(BPF_CFLAGS) + +.PHONY: check-clang +check-clang: + @command -v $(CLANG) >/dev/null 2>&1 || { \ + echo "$(CLANG) not found. Generating the eBPF objects needs clang $(CLANG_VERSION)."; \ + exit 1; \ + } + @command -v $(LLVM_STRIP) >/dev/null 2>&1 || { \ + echo "$(LLVM_STRIP) not found. Versioned llvm packages ship llvm-strip-$(CLANG_VERSION)"; \ + echo "without the unversioned name bpf2go looks for."; \ + echo "Point LLVM_STRIP at it, e.g. make ebpf LLVM_STRIP=llvm-strip-$(CLANG_VERSION)."; \ + exit 1; \ + } + @have=$$($(CLANG) --version | sed -n 's/.*clang version \([0-9]*\).*/\1/p' | head -1); \ + if [ "$$have" != "$(CLANG_VERSION)" ]; then \ + echo "clang $$have found but the committed objects were generated with $(CLANG_VERSION)."; \ + echo "Regenerating with another major rewrites every object and fails ebpf-drift."; \ + echo "Point CLANG at the right binary, e.g. make ebpf CLANG=clang-$(CLANG_VERSION)."; \ + exit 1; \ + fi + +# Regenerating must be reproducible: same sources and same clang, same bytes. +.PHONY: ebpf-drift +ebpf-drift: + $(MAKE) -B ebpf + git diff --exit-code -- $(BPF_OUT) + +ifeq ($(strip $(TAGS)),) +BUILD_TAGS := +else +BUILD_TAGS := -tags $(TAGS) +endif + +# Builds from the committed objects alone, so a fresh checkout needs no clang +# and no kernel headers. Naming the target pair keeps this buildable from a +# developer machine that is neither, which is the cheapest way to prove it. +.PHONY: build +build: + GOOS=linux GOARCH=$(TARGET_ARCH) $(GO) build $(BUILD_TAGS) -o ./cmd/fibratus/fibratus ./cmd/fibratus/ + +.PHONY: fmt +fmt: + $(GOFMT) -e -s -l -w pkg cmd internal + +TEST_PKGS := \ + ./internal/ebpf \ + ./internal/bootstrap \ + ./pkg/api \ + ./pkg/config \ + ./pkg/event \ + ./pkg/filter \ + ./pkg/ps \ + ./pkg/rules \ + ./pkg/rules/action \ + ./pkg/util/signals + +.PHONY: test +test: + $(GO) test $(TEST_PKGS) + +.PHONY: test-race +test-race: + $(GO) test -race $(TEST_PKGS) + +# Needs a 5.9+ kernel with runtime BTF, and root to load and attach. +.PHONY: test-integration +test-integration: + $(GO) test -tags ebpf_integration -count=1 ./internal/ebpf + +# Narrower than TEST_PKGS on purpose. Packages outside this set carry helpers +# that only Windows reaches, so `unused` reports them on every Linux run and +# there is nothing to fix without moving Windows code around. +LINT_PKGS := \ + ./internal/ebpf/... \ + ./internal/bootstrap/... \ + ./pkg/filter/... \ + ./pkg/rules/... + +.PHONY: lint +lint: + golangci-lint run $(LINT_PKGS) + +VERSION ?= 0.0.0 +PKG_DIR := build/pkg +NFPM ?= go run github.com/goreleaser/nfpm/v2/cmd/nfpm@$(NFPM_VERSION) + +.PHONY: pkg +pkg: build + @mkdir -p $(PKG_DIR) + VERSION=$(VERSION) $(NFPM) package --config build/linux/nfpm.yaml --packager deb --target $(PKG_DIR) + VERSION=$(VERSION) $(NFPM) package --config build/linux/nfpm.yaml --packager rpm --target $(PKG_DIR) + +.PHONY: clean +clean: + rm -f cmd/fibratus/fibratus + rm -rf $(PKG_DIR) diff --git a/build/linux/fibratus.service b/build/linux/fibratus.service new file mode 100644 index 000000000..3e0d265b0 --- /dev/null +++ b/build/linux/fibratus.service @@ -0,0 +1,44 @@ +[Unit] +Description=Fibratus +Documentation=https://www.fibratus.io +After=network.target + +[Service] +Type=simple +ExecStart=/usr/bin/fibratus run +Restart=on-failure +RestartSec=5s + +# Fibratus starts as root because attaching a syscall tracepoint reads its id +# from /sys/kernel/tracing, which is root-only on stock distributions. The +# bounding set is what actually constrains it: everything below is dropped, so +# the process keeps only what the backend and the kill action need. +# +# CAP_BPF load programs, create and update maps +# CAP_PERFMON attach to tracepoints +# CAP_SYS_PTRACE read /proc//exe and cmdline of other users' processes +# CAP_KILL signal a target, needed only by the kill rule action +# +# CAP_BPF and CAP_PERFMON were split out of CAP_SYS_ADMIN in 5.8. On a kernel +# that predates the split, replace both with CAP_SYS_ADMIN. +CapabilityBoundingSet=CAP_BPF CAP_PERFMON CAP_SYS_PTRACE CAP_KILL +AmbientCapabilities=CAP_BPF CAP_PERFMON CAP_SYS_PTRACE CAP_KILL +NoNewPrivileges=yes + +# full rather than strict: strict would also mount /run read-only and the API +# socket lives there. +ProtectSystem=full +ProtectHome=yes +PrivateTmp=yes +ProtectKernelTunables=yes +ProtectKernelModules=yes +ProtectControlGroups=yes +RestrictSUIDSGID=yes +LockPersonality=yes + +# Process enrichment reads other processes' procfs entries, so this must stay +# permissive. Hiding them would silently empty ps.exe and ps.cmdline. +ProtectProc=default + +[Install] +WantedBy=multi-user.target diff --git a/build/linux/nfpm.yaml b/build/linux/nfpm.yaml new file mode 100644 index 000000000..7d272a362 --- /dev/null +++ b/build/linux/nfpm.yaml @@ -0,0 +1,46 @@ +name: fibratus +arch: amd64 +platform: linux +version: ${VERSION} +section: admin +priority: optional +maintainer: Nedim Sabic Sabic +description: | + Security sensor for realtime threat detection and protection +vendor: Fibratus +homepage: https://fibratus.io +license: Apache-2.0 + +# The BPF objects are embedded in the binary at compile time, so there is +# nothing to ship alongside it. +contents: + - src: ./cmd/fibratus/fibratus + dst: /usr/bin/fibratus + + - src: ./configs/fibratus-linux.yml + dst: /etc/fibratus/fibratus.yml + type: config|noreplace + + - src: ./rules/linux/*.yml + dst: /etc/fibratus/rules/ + + - src: ./rules/linux/macros/macros.yml + dst: /etc/fibratus/rules/macros/macros.yml + + - src: ./build/linux/fibratus.service + dst: /lib/systemd/system/fibratus.service + +overrides: + rpm: + contents: + - src: ./cmd/fibratus/fibratus + dst: /usr/bin/fibratus + - src: ./configs/fibratus-linux.yml + dst: /etc/fibratus/fibratus.yml + type: config|noreplace + - src: ./rules/linux/*.yml + dst: /etc/fibratus/rules/ + - src: ./rules/linux/macros/macros.yml + dst: /etc/fibratus/rules/macros/macros.yml + - src: ./build/linux/fibratus.service + dst: /usr/lib/systemd/system/fibratus.service 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..4250ccca6 --- /dev/null +++ b/cmd/fibratus/app/root_linux.go @@ -0,0 +1,33 @@ +//go:build linux + +/* + * 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 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..8c698a0b0 --- /dev/null +++ b/cmd/fibratus/app/root_windows.go @@ -0,0 +1,36 @@ +//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 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..3de0b072a --- /dev/null +++ b/cmd/fibratus/app/run_linux.go @@ -0,0 +1,56 @@ +//go:build linux + +/* + * 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 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/app/stats/stats.go b/cmd/fibratus/app/stats/stats.go index 4232ee67a..8206de7da 100644 --- a/cmd/fibratus/app/stats/stats.go +++ b/cmd/fibratus/app/stats/stats.go @@ -44,78 +44,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"` - 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 new file mode 100644 index 000000000..67ac58257 --- /dev/null +++ b/cmd/fibratus/app/stats/stats_linux.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 stats + +// Stats stores runtime statistics that are retrieved from the expvar endpoint. +// Field order is the order the table renders in, so counters are grouped by the +// stage they describe: capture, then the kernel-side drops worth alerting on, +// then the startup handover, then the rule engine. +type Stats struct { + EventsProcessed int `json:"ebpf.events.processed"` + EventsExcluded int `json:"ebpf.events.excluded"` + EventsUnknown int `json:"ebpf.events.unknown"` + EventsParseErrs int `json:"ebpf.events.parse.errors"` + + RingbufDrops int `json:"ebpf.ringbuf.drops"` + ApproverDrops int `json:"ebpf.approver.drops"` + + EnrichmentMiss int `json:"ebpf.enrichment.miss"` + + StartupPendingQueued int `json:"ebpf.startup.pending.queued"` + StartupPendingDropped int `json:"ebpf.startup.pending.dropped"` + StartupReplayApplied int `json:"ebpf.startup.replay.applied"` + StartupSnapshotUpserts int `json:"ebpf.startup.snapshot.upserts"` + StartupSnapshotLate int `json:"ebpf.startup.snapshot.late"` + + FiltersCount int `json:"filter.filters.count"` + FilterMatches map[string]int `json:"filter.matches"` + + AggregatorBatchEvents int `json:"aggregator.batch.events"` + AggregatorFlushesCount int `json:"aggregator.flushes.count"` + AggregatorEventErrors int `json:"aggregator.event.errors"` +} 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/cmd/fibratus/main_linux.go b/cmd/fibratus/main_linux.go new file mode 100644 index 000000000..349a9c889 --- /dev/null +++ b/cmd/fibratus/main_linux.go @@ -0,0 +1,32 @@ +/* + * 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 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/configs/fibratus-linux.yml b/configs/fibratus-linux.yml new file mode 100644 index 000000000..51b9fb446 --- /dev/null +++ b/configs/fibratus-linux.yml @@ -0,0 +1,132 @@ +# Fibratus configuration for Linux. +# +# Only the settings that apply to the eBPF backend are listed here. Windows-only +# sections, such as filaments, PE introspection, YARA scanning, and handle or +# evasion telemetry, have no effect on this platform and are left out rather +# than shipped inert. + +# =============================== Event source ========================================= + +eventsource: + # Process telemetry is always collected. Execve, exit, and clone build the + # process state every other event is correlated against, so they cannot be + # disabled. + + # Collects openat, unlink, and rename. This is the highest-volume family by a + # wide margin on a busy host. + enable-fileio: true + + # Collects connect and accept. + enable-net: true + + # Collects mmap, process_vm_readv, and process_vm_writev. + enable-mem: true + + # Drops events before they reach the aggregator, by event name or by the + # image name of the process that produced them. + #blacklist: + # events: + # - openat + # images: + # - fibratus + +# =============================== Aggregator =========================================== + +aggregator: + # Determines the flush period that triggers the flushing of the event batches to output sinks + flush-period: 500ms + + # Represents the max time to wait before announcing failed flushing of enqueued events when fibratus + # is stopped + flush-timeout: 4s + +# =============================== Filters and rules ==================================== + +filters: + rules: + # Enables the rule engine. With no rules loaded every event reaches the + # outputs; with rules loaded only matching events do. + enabled: true + + # Rule definitions. The package installs the shipped Linux rules here. + from-paths: + - /etc/fibratus/rules/*.yml + + macros: + from-paths: + - /etc/fibratus/rules/macros/*.yml + +# =============================== API ================================================== + +api: + # The transport for the API HTTP server. A unix:// path keeps the API off the + # network and leaves access to the socket's filesystem permissions. A host:port + # value exposes it over TCP instead, e.g. 192.168.1.32:8084. + transport: unix:///var/run/fibratus.sock + + # Represents the timeout interval for the HTTP server responses. + timeout: 5s + +# =============================== Logging ============================================== + +logging: + # Specifies the minimum allowed log level. Anything logged below this log level will + # not get dumped to a file or stdout stream + level: info + + # Represents the log file format + #formatter: json + + # Under systemd, logging to stdout routes through the journal + log-stdout: true + + # Alternative directory for log files + #path: /var/log/fibratus + +# =============================== Outputs ============================================== + +output: + # Console output writes the event to the standard output stream. + console: + enabled: true + + # Indicates if the console output is colorized + colorize: true + + # The "pretty" format replaces specifiers in the template, "json" emits the + # event as a raw JSON string + format: pretty + + # Elasticsearch output indexes event bulks into Elasticsearch clusters. + elasticsearch: + enabled: false + #servers: + # - http://localhost:9200 + + # HTTP output posts event batches to an HTTP endpoint. + http: + enabled: false + #endpoint: http://localhost:8081 + + # AMQP output publishes events to a message broker. + amqp: + enabled: false + #url: amqp://localhost:5672 + +# =============================== Alert senders ======================================== + +alertsenders: + mail: + enabled: false + #host: smtp.gmail.com + #port: 587 + + slack: + enabled: false + #url: https://hooks.slack.com/services/... + +# =============================== General ============================================== + +# Forwards events to the output sinks without running the rule engine or +# building the full process state. +forward: false diff --git a/docs/_sidebar.md b/docs/_sidebar.md index 7d893b36c..8e8df8af5 100755 --- a/docs/_sidebar.md +++ b/docs/_sidebar.md @@ -2,6 +2,7 @@ * [Installation](setup/installation.md) * [Quick Start](setup/quick-start.md) * [Configuration](setup/configuration.md) + * [Linux](setup/linux.md) * --- * [Architecture](architecture.md) * --- diff --git a/docs/setup/linux.md b/docs/setup/linux.md new file mode 100644 index 000000000..d6d6f1a52 --- /dev/null +++ b/docs/setup/linux.md @@ -0,0 +1,152 @@ +# Linux + +On Linux, Fibratus collects telemetry through eBPF CO-RE programs attached to syscall and scheduler tracepoints, instead of ETW. The rule engine, filters, actions, and outputs are the same on both platforms. + +## Installing + +Packages are built for `x86_64` and carry the binary, a configuration, the shipped rules, and a systemd unit. The BPF objects are compiled into the binary, so there is nothing else to install and no compiler is needed on the host. + +``` +# Debian, Ubuntu +sudo dpkg -i fibratus__amd64.deb + +# RHEL, Fedora, Rocky, openSUSE +sudo rpm -i fibratus--1.x86_64.rpm +``` + +| Path | Contents | +| --- | --- | +| `/usr/bin/fibratus` | The binary | +| `/etc/fibratus/fibratus.yml` | Configuration, preserved across upgrades | +| `/etc/fibratus/rules/` | Shipped detection rules | +| `/etc/fibratus/rules/macros/` | Macros the rules expand | +| `/lib/systemd/system/fibratus.service` | Service unit, `/usr/lib/...` on RPM distributions | + +## Quick start + +Check the host before starting anything. This refuses to run and names every unmet requirement at once, rather than failing later inside the capture: + +``` +sudo fibratus rules validate +``` + +Run in the foreground to see events as they arrive: + +``` +sudo fibratus run +``` + +Narrow it with a filter expression, using the same language the rules use: + +``` +sudo fibratus run "evt.name = 'openat' and file.path startswith '/etc'" +``` + +Then run it as a service: + +``` +sudo systemctl enable --now fibratus +sudo systemctl status fibratus +sudo journalctl -u fibratus -f +``` + +The unit logs to the journal. With the rule engine enabled, only events matching a rule reach the outputs, so an idle host is expected to be quiet; drop the rules or set `filters.rules.enabled` to `false` to see the raw stream. + +Inspect a running instance over the API socket: + +``` +sudo fibratus config # the configuration as loaded +sudo fibratus stats # capture, drop, and rule engine counters +sudo fibratus list events +``` + +## Runtime prerequisites + +These are hard requirements. Fibratus probes each one at startup and refuses to run if any is missing, rather than degrading to partial telemetry. + +| Requirement | Why | +| --- | --- | +| Linux 5.9 or later | BPF task iterators, used to build the initial process tree, appear in 5.9 | +| Runtime kernel BTF at `/sys/kernel/btf/vmlinux` | CO-RE relocations and `iter/task` attachment resolve against the running kernel's own type information | +| `x86_64` | The shipped BPF objects are built for this architecture | +| Ring buffer map support | Events reach userspace through `BPF_MAP_TYPE_RINGBUF` | + +There is no BTFHub download and no embedded build-host BTF. A kernel compiled without `CONFIG_DEBUG_INFO_BTF` cannot run the backend, and no amount of configuration works around it. Most distribution kernels from 5.9 onwards enable it; if `/sys/kernel/btf/vmlinux` is absent, the kernel was built without it. + +Nothing needs to be compiled at install time. The BPF objects are generated ahead of time and committed, so neither clang nor kernel headers are required on the host. + +## Capabilities + +The packaged unit starts Fibratus as root, because attaching a syscall tracepoint reads its id from `/sys/kernel/tracing`, which is root-only on stock distributions. What limits it is the bounding set in the unit, which drops everything except the four capabilities below. Granting these to an unprivileged invocation works too, provided tracefs is readable: + +| Capability | Needed for | +| --- | --- | +| `CAP_BPF` | Loading programs and creating maps | +| `CAP_PERFMON` | Attaching to tracepoints | +| `CAP_SYS_PTRACE` | Reading `/proc//exe` and `/proc//cmdline` of processes owned by other users | +| `CAP_KILL` | Only if a rule uses the `kill` action against processes you do not own | + +`CAP_BPF` and `CAP_PERFMON` were split out of `CAP_SYS_ADMIN` in 5.8. On a kernel that predates the split, or on a distribution that has not adopted it, `CAP_SYS_ADMIN` is the equivalent. + +Two environment-specific cases override all of the above. Under kernel lockdown in `confidentiality` mode, loading tracing programs is refused no matter which capabilities you hold; check with `cat /sys/kernel/security/lockdown`. Below 5.11, BPF memory is charged against `RLIMIT_MEMLOCK`, so a low limit causes load failures that read as permission errors; Fibratus raises the limit at startup, which itself needs privilege. + +## Reading a failed startup + +Fibratus prints the probe result before anything else: + +``` +eBPF prerequisites ok: kernel=6.8.0-40-generic btf=/sys/kernel/btf/vmlinux ringbuf=true iter=true +``` + +When a prerequisite is missing it refuses to start and names every failure at once, so one run tells you everything that needs fixing: + +``` +eBPF prerequisites: kernel 5.4.0-91-generic is below required 5.9; usable kernel BTF required at /sys/kernel/btf/vmlinux +``` + +Failures after that line are attachment problems rather than prerequisite problems. `cannot create bpf perf link: permission denied` on an optional tracepoint is expected and harmless: `fork`, `vfork`, and the legacy `open`, `unlink`, and `rename` syscalls are skipped when the kernel refuses a perf link on them, because libc routes through `clone`, `openat`, `unlinkat`, and `renameat` anyway. The same message on a required tracepoint is fatal and means capabilities or lockdown. + +## Process enrichment + +The initial process tree comes from a single `iter/task` pass over `task_struct`, which is race-free against processes starting during startup. Executable paths and command lines are then filled in best effort from `/proc//exe` and `/proc//cmdline`. + +That second step is allowed to fail. A process that exits between the iterator pass and the procfs read leaves those two fields empty, and Fibratus counts it rather than dropping the process. Enrichment never replaces what the iterator produced, so a failed read cannot corrupt process identity. + +## Metrics + +Counters are exported as expvars and available through `fibratus stats`. + +| Metric | Meaning | +| --- | --- | +| `ebpf.events.processed` | Events decoded from the ring buffer | +| `ebpf.events.excluded` | Events dropped in userspace by config or filters | +| `ebpf.events.unknown` | Records carrying a type this build does not know | +| `ebpf.events.parse.errors` | Malformed ring buffer records | +| `ebpf.ringbuf.drops` | Events the kernel could not queue because the ring buffer was full | +| `ebpf.approver.drops` | Events rejected in the kernel by an approver, before reaching the ring buffer | +| `ebpf.enrichment.miss` | Processes whose procfs enrichment failed | +| `ebpf.startup.pending.queued` | Live events buffered while the baseline scan ran | +| `ebpf.startup.pending.dropped` | Live events discarded because that buffer was full | +| `ebpf.startup.replay.applied` | Buffered events replayed once the baseline completed | +| `ebpf.startup.snapshot.upserts` | Processes recorded by the baseline scan | +| `ebpf.startup.snapshot.late` | Baseline records that arrived after the switch to live dispatch | + +`ebpf.ringbuf.drops` growing steadily is the signal that consumers are not keeping up; it is the one counter worth alerting on. `ebpf.approver.drops` growing is normal and desirable, since it counts work avoided. + +## Building from source + +Ordinary builds consume the committed objects: + +``` +make # the binary +make pkg # deb and rpm into build/pkg +``` + +Regenerating them needs clang, pinned to the major the committed objects were built with, because clang records its version in BTF and a different major rewrites every object: + +``` +make ebpf # regenerate +make ebpf-drift # regenerate and fail if the result differs from what is committed +``` + +Other targets: `make test`, `make test-race`, `make lint`, and `make test-integration`, which needs root and a host meeting the prerequisites above. diff --git a/go.mod b/go.mod index 77416beba..4644144e7 100644 --- a/go.mod +++ b/go.mod @@ -6,6 +6,7 @@ require ( github.com/antchfx/htmlquery v1.2.5 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 @@ -47,9 +48,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.11.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 b1ad4f534..549213ce9 100644 --- a/go.sum +++ b/go.sum @@ -26,13 +26,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= @@ -56,6 +57,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= @@ -102,6 +105,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= @@ -134,6 +141,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= @@ -150,7 +161,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= @@ -175,9 +185,8 @@ 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.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= diff --git a/internal/bootstrap/bootstrap_linux.go b/internal/bootstrap/bootstrap_linux.go new file mode 100644 index 000000000..25dc8bdf9 --- /dev/null +++ b/internal/bootstrap/bootstrap_linux.go @@ -0,0 +1,225 @@ +//go:build linux + +/* + * 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 bootstrap + +import ( + "context" + "errors" + "fmt" + "net" + "os" + + "github.com/rabbitstack/fibratus/pkg/aggregator" + "github.com/rabbitstack/fibratus/pkg/alertsender" + "github.com/rabbitstack/fibratus/pkg/api" + "github.com/rabbitstack/fibratus/pkg/config" + "github.com/rabbitstack/fibratus/pkg/filter" + "github.com/rabbitstack/fibratus/pkg/ps" + "github.com/rabbitstack/fibratus/pkg/rules" + "github.com/rabbitstack/fibratus/pkg/util/multierror" + "github.com/rabbitstack/fibratus/pkg/util/signals" + "github.com/rabbitstack/fibratus/pkg/util/version" + log "github.com/sirupsen/logrus" +) + +// instanceSocket is an abstract UNIX domain socket name. Binding it acts as +// a kernel-wide mutex that is released automatically when the process +// terminates, so no filesystem cleanup is required. +const instanceSocket = "@fibratus" + +// ErrAlreadyRunning signals a Fibratus process is already running. +var ErrAlreadyRunning = errors.New("an instance of Fibratus process is already running in the system") + +// App centralizes the core building blocks responsible +// for event acquisition, rule engine initialization, +// and event routing to the output sinks. +type App struct { + config *config.Config + evs *EventSourceControl + engine *rules.Engine + psnap ps.Snapshotter + agg *aggregator.BufferedAggregator + signals chan struct{} + instance net.Listener + server *api.Server +} + +// Option enables changing the behaviour of the bootstrap application. +type Option func(*opts) + +type opts struct { + installSignals bool +} + +// WithSignals installs signal handlers. +func WithSignals() Option { + return func(o *opts) { + o.installSignals = true + } +} + +// NewApp constructs a new bootstrap application with the specified configuration +// and a list of options. +func NewApp(cfg *config.Config, options ...Option) (*App, error) { + if err := InitConfigAndLogger(cfg); err != nil { + return nil, err + } + var o opts + var sigs chan struct{} + for _, opt := range options { + opt(&o) + } + if o.installSignals { + sigs = signals.Install() + } + + psnap := ps.NewSnapshotter() + + var engine *rules.Engine + var rs *config.RulesCompileResult + var plan *filter.ApproverPlan + if cfg.Filters != nil && cfg.Filters.Rules.Enabled && !cfg.ForwardMode && !cfg.IsCaptureSet() && !cfg.IsFilamentSet() { + engine = rules.NewEngine(psnap, cfg) + var err error + rs, err = engine.Compile() + if err != nil { + return nil, err + } + plan = engine.ApproverPlan() + if rs != nil { + log.Infof("rules compile summary: %s", rs) + } + } else { + log.Info("rule engine is disabled") + } + + server, err := api.NewServer(cfg) + if err != nil { + return nil, err + } + + return &App{ + config: cfg, + evs: NewEventSourceControl(psnap, cfg, rs, plan), + engine: engine, + psnap: psnap, + signals: sigs, + server: server, + }, nil +} + +// Run configures and opens the event source to start consuming events. +func (f *App) Run(args []string) error { + if f.evs == nil { + panic("event source is nil") + } + cfg := f.config + + if cfg.IsFilamentSet() { + return fmt.Errorf("filaments are not supported on Linux") + } + + if !f.isSingleInstance() { + return ErrAlreadyRunning + } + + log.Infof("bootstrapping with pid %d. Version: %s", os.Getpid(), version.Get()) + log.Infof("configuration options: %s", cfg.Print()) + + fltr, err := filter.NewFromCLI(args, cfg) + if err != nil { + return err + } + if fltr != nil { + f.evs.SetFilter(fltr) + } + if f.engine != nil { + f.evs.RegisterEventListener(f.engine) + } + + if err := f.evs.Open(cfg); err != nil { + return multierror.Wrap(err, f.evs.Close()) + } + + f.agg, err = aggregator.NewBuffered( + f.evs.Events(), + f.evs.Errors(), + cfg.Aggregator, + cfg.Output, + cfg.Transformers, + cfg.Alertsenders, + ) + if err != nil { + return err + } + f.server.Start() + return nil +} + +// Wait waits for the app to receive the termination signal. +func (f *App) Wait() { + if f.signals != nil { + <-f.signals + } +} + +// Shutdown is responsible for tearing down everything gracefully. +func (f *App) Shutdown() error { + errs := make([]error, 0) + if f.evs != nil { + if err := f.evs.Close(); err != nil { + errs = append(errs, err) + } + } + if f.psnap != nil { + if err := f.psnap.Close(); err != nil { + errs = append(errs, err) + } + } + if f.agg != nil { + if err := f.agg.Stop(); err != nil { + errs = append(errs, err) + } + } + if err := f.server.Stop(context.Background()); err != nil { + errs = append(errs, err) + } + if err := alertsender.ShutdownAll(); err != nil { + errs = append(errs, err) + } + if f.instance != nil { + _ = f.instance.Close() + } + return multierror.Wrap(errs...) +} + +// isSingleInstance checks if there is already an instance of Fibratus +// running in the system. +func (f *App) isSingleInstance() bool { + var lc net.ListenConfig + l, err := lc.Listen(context.Background(), "unix", instanceSocket) + if err != nil { + return false + } + f.instance = l + return true +} diff --git a/internal/bootstrap/bootstrap.go b/internal/bootstrap/bootstrap_windows.go similarity index 96% rename from internal/bootstrap/bootstrap.go rename to internal/bootstrap/bootstrap_windows.go index 1e5a52361..29307ce6d 100644 --- a/internal/bootstrap/bootstrap.go +++ b/internal/bootstrap/bootstrap_windows.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2021-2022 by Nedim Sabic Sabic * https://www.fibratus.io @@ -65,6 +67,7 @@ type App struct { writer cap.Writer reader cap.Reader signals chan struct{} + server *api.Server } // Option enables changing the behaviour of the bootstrap application. @@ -124,6 +127,10 @@ func NewApp(cfg *config.Config, options ...Option) (*App, error) { sigs = signals.Install() } if opts.isCaptureReplay { + server, err := api.NewServer(cfg) + if err != nil { + return nil, err + } reader, err := cap.NewReader(cfg.CapFile, cfg) if err != nil { return nil, err @@ -132,6 +139,7 @@ func NewApp(cfg *config.Config, options ...Option) (*App, error) { config: cfg, reader: reader, signals: sigs, + server: server, } return app, nil } @@ -161,6 +169,11 @@ func NewApp(cfg *config.Config, options ...Option) (*App, error) { evs := NewEventSourceControl(psnap, hsnap, cfg, rs) + server, err := api.NewServer(cfg) + if err != nil { + return nil, err + } + app := &App{ config: cfg, evs: evs, @@ -168,6 +181,7 @@ func NewApp(cfg *config.Config, options ...Option) (*App, error) { hsnap: hsnap, psnap: psnap, signals: sigs, + server: server, } return app, nil @@ -273,8 +287,8 @@ func (f *App) Run(args []string) error { return err } } - // start the HTTP server - return api.StartServer(cfg) + f.server.Start() + return nil } // WriteCapture writes the event stream to the capture file. @@ -308,7 +322,10 @@ func (f *App) WriteCapture(args []string) error { log.Warnf("fail to write event to capture: %v", err) } }() - return api.StartServer(f.config) + + f.server.Start() + + return nil } // ReadCapture reconstructs the event stream from the capture file. @@ -365,8 +382,8 @@ func (f *App) ReadCapture(ctx context.Context, args []string) error { return err } } - - return api.StartServer(f.config) + f.server.Start() + return nil } // Wait waits for the app to receive the termination signal. @@ -420,7 +437,7 @@ func (f *App) Shutdown() error { if err := handle.CloseTimeout(); err != nil { errs = append(errs, err) } - if err := api.CloseServer(); err != nil { + if err := f.server.Stop(context.Background()); err != nil { errs = append(errs, err) } if err := alertsender.ShutdownAll(); err != nil { diff --git a/internal/bootstrap/config.go b/internal/bootstrap/config.go index 81c56e904..b02cb88fa 100644 --- a/internal/bootstrap/config.go +++ b/internal/bootstrap/config.go @@ -19,10 +19,11 @@ package bootstrap import ( + "os" + "github.com/rabbitstack/fibratus/pkg/config" "github.com/rabbitstack/fibratus/pkg/util/log" "github.com/sirupsen/logrus" - "os" ) // InitConfigAndLogger initializes the configuration and sets up the logger. diff --git a/internal/bootstrap/source_linux.go b/internal/bootstrap/source_linux.go new file mode 100644 index 000000000..69765e6d9 --- /dev/null +++ b/internal/bootstrap/source_linux.go @@ -0,0 +1,69 @@ +//go:build linux + +/* + * 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 bootstrap + +import ( + libebpf "github.com/rabbitstack/fibratus/internal/ebpf" + "github.com/rabbitstack/fibratus/pkg/config" + "github.com/rabbitstack/fibratus/pkg/event" + "github.com/rabbitstack/fibratus/pkg/filter" + "github.com/rabbitstack/fibratus/pkg/ps" + "github.com/rabbitstack/fibratus/pkg/source" +) + +// EventSourceControl abstracts away the management of event sources. +type EventSourceControl struct { + evs source.EventSource +} + +func NewEventSourceControl( + psnap ps.Snapshotter, + cfg *config.Config, + compiler *config.RulesCompileResult, + plan *filter.ApproverPlan, +) *EventSourceControl { + return &EventSourceControl{evs: libebpf.NewEventSource(psnap, cfg, compiler, plan)} +} + +func (s *EventSourceControl) Open(cfg *config.Config) error { + return s.evs.Open(cfg) +} + +func (s *EventSourceControl) Close() error { + return s.evs.Close() +} + +func (s *EventSourceControl) Errors() <-chan error { + return s.evs.Errors() +} + +func (s *EventSourceControl) Events() <-chan *event.Event { + return s.evs.Events() +} + +func (s *EventSourceControl) SetFilter(f filter.Filter) { + s.evs.SetFilter(f) +} + +func (s *EventSourceControl) RegisterEventListener(lis event.Listener) { + s.evs.RegisterEventListener(lis) +} diff --git a/internal/bootstrap/source.go b/internal/bootstrap/source_windows.go similarity index 99% rename from internal/bootstrap/source.go rename to internal/bootstrap/source_windows.go index 683ee22f9..05931d682 100644 --- a/internal/bootstrap/source.go +++ b/internal/bootstrap/source_windows.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2021-2022 by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/internal/ebpf/FEASIBILITY.md b/internal/ebpf/FEASIBILITY.md new file mode 100644 index 000000000..46aa7d58b --- /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 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: + +- 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 (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 | +| 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 diff --git a/internal/ebpf/approver.go b/internal/ebpf/approver.go new file mode 100644 index 000000000..7a51a715b --- /dev/null +++ b/internal/ebpf/approver.go @@ -0,0 +1,257 @@ +//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 ebpf + +import ( + "fmt" + + "github.com/cilium/ebpf" + "github.com/rabbitstack/fibratus/internal/ebpf/bpf" + "github.com/rabbitstack/fibratus/pkg/event" + "github.com/rabbitstack/fibratus/pkg/filter" +) + +func (l *loader) populateApprovers(plan *filter.ApproverPlan) error { + if l == nil || l.exec == nil { + return fmt.Errorf("approver maps are not loaded") + } + if plan == nil { + plan = filter.AllowAllPlan() + } + + cur, err := l.approverGen() + if err != nil { + return err + } + inactive := uint32(1) - cur + if err := l.clearGeneration(inactive); err != nil { + return fmt.Errorf("clearing inactive approver generation: %w", err) + } + if err := l.writePlan(inactive, plan); err != nil { + return err + } + // The retired generation is left populated on purpose. A program that read + // the old generation before the flip still resolves its lookups against it; + // wiping it here would turn those in-flight events into drops. The next + // reload clears it before reusing it. + if err := l.exec.ApproverGen.Put(uint32(0), inactive); err != nil { + return fmt.Errorf("flipping approver generation: %w", err) + } + return nil +} + +func (l *loader) approverGen() (uint32, error) { + var key, gen uint32 + if err := l.exec.ApproverGen.Lookup(&key, &gen); err != nil { + return 0, fmt.Errorf("reading approver generation: %w", err) + } + return gen & 1, nil +} + +func (l *loader) approverRejects() uint64 { + var key uint32 + var n uint64 + if l.exec == nil || l.exec.ApproverReject == nil { + return 0 + } + _ = l.exec.ApproverReject.Lookup(&key, &n) + return n +} + +func (l *loader) writePlan(gen uint32, plan *filter.ApproverPlan) error { + for i := uint32(0); i < approverTypeMax; i++ { + key := gen*approverTypeMax + i + typ := event.Type(i) + pol := plan.Policy(typ) + mode := policyMode(pol, typ) + if err := l.exec.ApproverMode.Put(&key, &mode); err != nil { + return fmt.Errorf("writing approver mode for type %d: %w", i, err) + } + if mode == 0 { + continue + } + if err := l.writePolicy(gen, typ, pol); err != nil { + return err + } + } + return nil +} + +func policyMode(pol filter.TypePolicy, typ event.Type) uint8 { + if filter.AlwaysAllowed(typ) || pol.DefaultAllow { + return 0 + } + var mode uint8 + if pol.RequirePID { + mode |= approverReqPID + } + if pol.RequireFilename { + mode |= approverReqFile + } + // The kernel only parses a destination port out of the stashed sockaddr for + // connect. Enforcing a port on any other type would compare against zero and + // drop everything, so those types keep the rest of their policy instead. + if pol.RequirePort && typ == event.Connect { + mode |= approverReqPort + } + return mode +} + +func (l *loader) writePolicy(gen uint32, typ event.Type, pol filter.TypePolicy) error { + id := uint32(typ) + present := uint8(1) + if pol.RequirePID { + for _, pid := range pol.PIDs { + key := bpf.ExecveApproverPidKey{Gen: gen, Type: id, Pid: pid} + if err := l.exec.ApproverPid.Put(&key, &present); err != nil { + return fmt.Errorf("writing pid approver: %w", err) + } + } + } + if pol.RequirePort && typ == event.Connect { + for _, port := range pol.Ports { + key := bpf.ExecveApproverPortKey{Gen: gen, Type: id, Port: port} + if err := l.exec.ApproverPort.Put(&key, &present); err != nil { + return fmt.Errorf("writing port approver: %w", err) + } + } + } + if pol.RequireFilename { + for _, path := range pol.FileExact { + key := bpf.ExecveApproverFileKey{Gen: gen, Type: id} + copy(key.Path[:], path) + if err := l.exec.ApproverFileEq.Put(&key, &present); err != nil { + return fmt.Errorf("writing file approver: %w", err) + } + } + pre := l.prefixMap(gen) + if pre == nil { + return fmt.Errorf("missing filename prefix map for generation %d", gen) + } + for _, prefix := range pol.FilePrefix { + if prefix == "" || len(prefix) > len(bpf.ExecveApproverLpmKey{}.Path) { + continue + } + key := bpf.ExecveApproverLpmKey{Prefixlen: uint32(len(prefix) * 8)} + copy(key.Path[:], prefix) + if err := pre.Put(&key, &present); err != nil { + return fmt.Errorf("writing file prefix approver: %w", err) + } + } + } + return nil +} + +func (l *loader) prefixMap(gen uint32) *ebpf.Map { + if gen == 0 { + return l.exec.ApproverFilePre0 + } + return l.exec.ApproverFilePre1 +} + +func (l *loader) clearGeneration(gen uint32) error { + if err := deleteHashGen(l.exec.ApproverPid, gen, func(k bpf.ExecveApproverPidKey) uint32 { return k.Gen }); err != nil { + return err + } + if err := deleteHashGen(l.exec.ApproverPort, gen, func(k bpf.ExecveApproverPortKey) uint32 { return k.Gen }); err != nil { + return err + } + if err := deleteHashGen(l.exec.ApproverFileEq, gen, func(k bpf.ExecveApproverFileKey) uint32 { return k.Gen }); err != nil { + return err + } + if err := deleteAll(l.prefixMap(gen)); err != nil { + return err + } + for i := uint32(0); i < approverTypeMax; i++ { + key := gen*approverTypeMax + i + var mode uint8 + if err := l.exec.ApproverMode.Put(&key, &mode); err != nil { + return err + } + } + return nil +} + +func deleteHashGen[K any](m *ebpf.Map, gen uint32, genOf func(K) uint32) error { + if m == nil { + return fmt.Errorf("missing approver map") + } + var key K + var val uint8 + stale := make([]K, 0) + iter := m.Iterate() + for iter.Next(&key, &val) { + if genOf(key) == gen { + stale = append(stale, key) + } + } + if err := iter.Err(); err != nil { + return err + } + for i := range stale { + if err := m.Delete(&stale[i]); err != nil { + return err + } + } + return nil +} + +func deleteAll(m *ebpf.Map) error { + if m == nil { + return fmt.Errorf("missing approver map") + } + var key bpf.ExecveApproverLpmKey + var val uint8 + stale := make([]bpf.ExecveApproverLpmKey, 0) + iter := m.Iterate() + for iter.Next(&key, &val) { + stale = append(stale, key) + } + if err := iter.Err(); err != nil { + return err + } + for i := range stale { + if err := m.Delete(&stale[i]); err != nil { + return err + } + } + return nil +} + +func sharedMaps(exec *bpf.ExecveObjects) map[string]*ebpf.Map { + return map[string]*ebpf.Map{ + eventsMapName: exec.Events, + dropCountMapName: exec.DropCount, + scratchMapName: exec.Scratch, + scratchHeapMapName: exec.ScratchHeap, + enabledMapName: exec.Enabled, + approverGenMapName: exec.ApproverGen, + approverModeMapName: exec.ApproverMode, + approverPIDMapName: exec.ApproverPid, + approverPortMapName: exec.ApproverPort, + approverFileEqMapName: exec.ApproverFileEq, + approverFilePre0Name: exec.ApproverFilePre0, + approverFilePre1Name: exec.ApproverFilePre1, + approverFileHeapName: exec.ApproverFileHeap, + approverLPMHeapName: exec.ApproverLpmHeap, + approverRejectMapName: exec.ApproverReject, + } +} diff --git a/internal/ebpf/approver_integration_test.go b/internal/ebpf/approver_integration_test.go new file mode 100644 index 000000000..a29af5e27 --- /dev/null +++ b/internal/ebpf/approver_integration_test.go @@ -0,0 +1,189 @@ +//go:build linux && ebpf_integration + +/* + * 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 ebpf + +import ( + "fmt" + "os" + "os/exec" + "path/filepath" + "testing" + "time" + + "github.com/rabbitstack/fibratus/pkg/event" + "github.com/rabbitstack/fibratus/pkg/event/params" + "github.com/rabbitstack/fibratus/pkg/filter" + "github.com/rabbitstack/fibratus/pkg/ps" + "github.com/stretchr/testify/require" +) + +// TestApproverDecisionsMatchLoadedPrograms exercises the compiled BPF logic +// rather than the Go model in ApproverPlan.Allows. The two are separate +// implementations of the same predicate, so the soundness property is only +// worth as much as this test. +func TestApproverDecisionsMatchLoadedPrograms(t *testing.T) { + dir := t.TempDir() + allowed := filepath.Join(dir, "allowed.txt") + require.NoError(t, os.WriteFile(allowed, []byte("x"), 0o600)) + + // Establish first that the capture path reports this exact open with no + // approver installed. If that fails, the problem is the enter/exit + // correlation rather than the prefilter, and the second phase would + // otherwise blame the approver for it. + baseline := watchOpens(t, nil, allowed) + require.True(t, baseline.sawAllowed, + "capture never reported the open with no approver installed; pid=%d selfOpens=%d saw %q", + os.Getpid(), baseline.selfOpens, baseline.seen) + + // Written as a matches pattern rather than startswith so the rewrite into + // the LPM trie is covered too. + plan := filter.PlanFromFilter(mustCompile(t, + "evt.name = 'openat' and file.path matches '"+dir+"/*'")) + got := watchOpens(t, plan, allowed) + + require.True(t, got.sawAllowed, + "openat matching the approved pattern never reached userspace; wanted %q, selfOpens=%d saw %q, rejects %d -> %d", + allowed, got.selfOpens, got.seen, got.rejectsBefore, got.rejectsAfter) + require.False(t, got.sawDenied, "openat outside the approved pattern reached userspace") + require.Greater(t, got.rejectsAfter, got.rejectsBefore, "approver reject counter did not advance") +} + +type openWatch struct { + sawAllowed bool + sawDenied bool + seen []string + selfOpens int + rejectsBefore uint64 + rejectsAfter uint64 +} + +const deniedPath = "/etc/hostname" + +// watchOpens repeatedly opens allowed and a denied path while draining events, +// returning what reached userspace. Correlating sys_enter_openat with its exit +// goes through a bounded LRU map, so on a loaded machine any single open can +// lose its scratch entry and arrive with no path at all. Retrying keeps the +// assertions about the approver rather than about that. +func watchOpens(t *testing.T, plan *filter.ApproverPlan, allowed string) openWatch { + t.Helper() + cfg := testConfig() + es := NewEventSource(ps.NewSnapshotter(), cfg, nil, plan).(*EventSource) + require.NoError(t, es.Open(cfg)) + defer func() { _ = es.Close() }() + + w := openWatch{seen: make([]string, 0, 16), rejectsBefore: es.loader.approverRejects()} + + attempts := time.NewTicker(200 * time.Millisecond) + defer attempts.Stop() + touch := func() { openFromChild(t, allowed) } + touch() + + deadline := time.Now().Add(20 * time.Second) + for time.Now().Before(deadline) && !w.sawAllowed { + select { + case evt := <-es.Events(): + if evt.Type != event.Openat { + continue + } + path := evt.GetParamAsString(params.FilePath) + if evt.PID == uint64(os.Getpid()) { + w.selfOpens++ + } + if len(w.seen) < cap(w.seen) { + w.seen = append(w.seen, fmt.Sprintf("pid=%d sys=%d %s", + evt.PID, evt.GetParamAsUint32(params.SyscallID), path)) + } + switch path { + case allowed: + w.sawAllowed = true + case deniedPath: + w.sawDenied = true + } + case err := <-es.Errors(): + t.Fatalf("event source error: %v", err) + case <-attempts.C: + touch() + } + } + w.rejectsAfter = es.loader.approverRejects() + return w +} + +// openFromChild opens the two paths from a short-lived child rather than from +// the test process. Syscall tracepoints did not report this process's own opens +// on every runner, while child processes are reported reliably, which is also +// how the other privileged tests here drive syscalls. +func openFromChild(t *testing.T, allowed string) { + t.Helper() + cmd := exec.Command("/bin/sh", "-c", "cat -- \"$1\" >/dev/null 2>&1; cat -- \"$2\" >/dev/null 2>&1", + "sh", allowed, deniedPath) + _ = cmd.Run() +} + +func TestApproverGenerationFlipAndFailedReload(t *testing.T) { + ldr, err := loadCollections() + if err != nil { + t.Fatalf("loading collections: %v", err) + } + t.Cleanup(func() { _ = ldr.Close() }) + + plan := filter.PlanFromFilter(mustCompile(t, "evt.name = 'openat' and file.path startswith '/tmp'")) + require.NoError(t, ldr.populateApprovers(plan)) + gen, err := ldr.approverGen() + require.NoError(t, err) + require.Equal(t, uint32(1), gen) + + require.NoError(t, ldr.populateApprovers(plan)) + gen, err = ldr.approverGen() + require.NoError(t, err) + require.Equal(t, uint32(0), gen) + + oversized := filter.BuildApproverPlan(manyPrefixFilters(t, 300)) + require.Error(t, ldr.populateApprovers(oversized)) + still, err := ldr.approverGen() + require.NoError(t, err) + require.Equal(t, gen, still) +} + +func mustCompile(t *testing.T, expr string) filter.Filter { + t.Helper() + f := filter.New(expr, testConfig()) + require.NoError(t, f.Compile()) + return f +} + +func manyPrefixFilters(t *testing.T, n int) []filter.Filter { + t.Helper() + out := make([]filter.Filter, 0, n) + for i := 0; i < n; i++ { + expr := "evt.name = 'openat' and file.path startswith '" + "/t" + itoa3(i) + "'" + out = append(out, mustCompile(t, expr)) + } + return out +} + +func itoa3(n int) string { + return string([]byte{ + byte('0' + (n/100)%10), + byte('0' + (n/10)%10), + byte('0' + n%10), + }) +} diff --git a/internal/ebpf/approver_test.go b/internal/ebpf/approver_test.go new file mode 100644 index 000000000..36ad5eb23 --- /dev/null +++ b/internal/ebpf/approver_test.go @@ -0,0 +1,125 @@ +//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 ebpf + +import ( + "testing" + + "github.com/rabbitstack/fibratus/internal/ebpf/bpf" + "github.com/rabbitstack/fibratus/pkg/config" + "github.com/rabbitstack/fibratus/pkg/event" + "github.com/rabbitstack/fibratus/pkg/filter" + "github.com/rabbitstack/fibratus/pkg/ps" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestSetFilterStoresBeforeOpen(t *testing.T) { + cfg := testConfig() + es := NewEventSource(ps.NewSnapshotter(), cfg, nil, nil).(*EventSource) + f := filter.New("evt.name = 'openat' and file.path startswith '/tmp'", cfg) + require.NoError(t, f.Compile()) + es.SetFilter(f) + require.NotNil(t, es.cliPlan) + pol := es.cliPlan.Policy(event.Openat) + require.False(t, pol.DefaultAllow) + assert.True(t, pol.RequireFilename) + assert.Nil(t, es.loader) +} + +func TestReloadApproversWithoutMapsIsNoop(t *testing.T) { + es := NewEventSource(ps.NewSnapshotter(), testConfig(), nil, nil).(*EventSource) + require.NoError(t, es.reloadApprovers()) +} + +func TestPolicyModeKeepsProcessState(t *testing.T) { + pol := filter.TypePolicy{RequireFilename: true, FilePrefix: []string{"/tmp"}} + assert.Equal(t, uint8(0), policyMode(pol, event.Execve)) + assert.Equal(t, uint8(0), policyMode(pol, event.Exit)) + assert.Equal(t, uint8(0), policyMode(pol, event.Clone)) + assert.Equal(t, uint8(approverReqFile), policyMode(pol, event.Openat)) +} + +func TestModeArrayMatchesGeneratedMap(t *testing.T) { + spec, err := bpf.LoadExecve() + require.NoError(t, err) + require.Equal(t, uint32(approverTypeMax*2), spec.Maps[approverModeMapName].MaxEntries, + "approverTypeMax must mirror EVT_TYPE_MAX in c/common/approvers.h") +} + +func BenchmarkApproverReduction(b *testing.B) { + cfg := &config.Config{ + EventSource: config.EventSourceConfig{EnableFileIOEvents: true}, + Filters: &config.Filters{}, + } + f := filter.New("evt.name = 'openat' and file.path startswith '/tmp'", cfg) + if err := f.Compile(); err != nil { + b.Fatal(err) + } + plan := filter.PlanFromFilter(f) + paths := []string{"/tmp/a", "/tmp/b", "/var/log/syslog", "/etc/passwd", "/usr/bin/ls"} + kept := 0 + b.ResetTimer() + for i := 0; i < b.N; i++ { + s := filter.Sample{Type: event.Openat, Filename: paths[i%len(paths)]} + if plan.Allows(s) { + kept++ + } + } + b.StopTimer() + if b.N > 0 { + b.ReportMetric(float64(b.N-kept)/float64(b.N), "drop_ratio") + } +} + +func TestApproverSoundnessTable(t *testing.T) { + cfg := testConfig() + cases := []struct { + expr string + keep filter.Sample + drop filter.Sample + }{ + { + expr: "evt.name = 'openat' and file.path startswith '/tmp'", + keep: filter.Sample{Type: event.Openat, Filename: "/tmp/x"}, + drop: filter.Sample{Type: event.Openat, Filename: "/etc/passwd"}, + }, + { + expr: "evt.name = 'connect' and net.dport in (80, 443)", + keep: filter.Sample{Type: event.Connect, Port: 443}, + drop: filter.Sample{Type: event.Connect, Port: 22}, + }, + { + expr: "evt.name = 'kill' and ps.pid = 9", + keep: filter.Sample{Type: event.Kill, PID: 9}, + drop: filter.Sample{Type: event.Kill, PID: 1}, + }, + } + for _, tt := range cases { + t.Run(tt.expr, func(t *testing.T) { + f := filter.New(tt.expr, cfg) + require.NoError(t, f.Compile()) + plan := filter.PlanFromFilter(f) + assert.True(t, plan.Allows(tt.keep), tt.expr) + assert.False(t, plan.Allows(tt.drop), tt.expr) + }) + } +} diff --git a/internal/ebpf/bpf/clone_bpfeb.go b/internal/ebpf/bpf/clone_bpfeb.go new file mode 100644 index 000000000..d3d15e461 --- /dev/null +++ b/internal/ebpf/bpf/clone_bpfeb.go @@ -0,0 +1,241 @@ +// Code generated by bpf2go; DO NOT EDIT. +//go:build (mips || mips64 || ppc64 || s390x) && linux + +package bpf + +import ( + "bytes" + _ "embed" + "fmt" + "io" + "structs" + + "github.com/cilium/ebpf" +) + +type CloneApproverFileKey struct { + _ structs.HostLayout + Gen uint32 + Type uint32 + Path [256]uint8 +} + +type CloneApproverLpmKey struct { + _ structs.HostLayout + Prefixlen uint32 + Path [256]uint8 +} + +type CloneApproverPidKey struct { + _ structs.HostLayout + Gen uint32 + Type uint32 + Pid uint64 +} + +type CloneApproverPortKey struct { + _ structs.HostLayout + Gen uint32 + Type uint32 + Port uint16 + Pad uint16 +} + +type CloneScratchValue struct { + _ structs.HostLayout + Arg0 uint64 + Arg1 uint64 + Arg2 uint64 + Arg3 uint64 + Flags uint64 + Truncated uint32 + Pad uint32 + Filename [256]uint8 + Aux [256]uint8 +} + +// LoadClone returns the embedded CollectionSpec for Clone. +func LoadClone() (*ebpf.CollectionSpec, error) { + reader := bytes.NewReader(_CloneBytes) + spec, err := ebpf.LoadCollectionSpecFromReader(reader) + if err != nil { + return nil, fmt.Errorf("can't load Clone: %w", err) + } + + return spec, err +} + +// LoadCloneObjects loads Clone and converts it into a struct. +// +// The following types are suitable as obj argument: +// +// *CloneObjects +// *ClonePrograms +// *CloneMaps +// +// See ebpf.CollectionSpec.LoadAndAssign documentation for details. +func LoadCloneObjects(obj interface{}, opts *ebpf.CollectionOptions) error { + spec, err := LoadClone() + if err != nil { + return err + } + + return spec.LoadAndAssign(obj, opts) +} + +// CloneSpecs contains maps and programs before they are loaded into the kernel. +// +// It can be passed ebpf.CollectionSpec.Assign. +type CloneSpecs struct { + CloneProgramSpecs + CloneMapSpecs + CloneVariableSpecs +} + +// CloneProgramSpecs contains programs before they are loaded into the kernel. +// +// It can be passed ebpf.CollectionSpec.Assign. +type CloneProgramSpecs struct { + HandleSchedProcessFork *ebpf.ProgramSpec `ebpf:"handle_sched_process_fork"` + HandleSysEnterClone *ebpf.ProgramSpec `ebpf:"handle_sys_enter_clone"` + HandleSysEnterClone3 *ebpf.ProgramSpec `ebpf:"handle_sys_enter_clone3"` + HandleSysEnterFork *ebpf.ProgramSpec `ebpf:"handle_sys_enter_fork"` + HandleSysEnterVfork *ebpf.ProgramSpec `ebpf:"handle_sys_enter_vfork"` + HandleSysExitClone *ebpf.ProgramSpec `ebpf:"handle_sys_exit_clone"` + HandleSysExitClone3 *ebpf.ProgramSpec `ebpf:"handle_sys_exit_clone3"` + HandleSysExitFork *ebpf.ProgramSpec `ebpf:"handle_sys_exit_fork"` + HandleSysExitVfork *ebpf.ProgramSpec `ebpf:"handle_sys_exit_vfork"` +} + +// CloneMapSpecs contains maps before they are loaded into the kernel. +// +// It can be passed ebpf.CollectionSpec.Assign. +type CloneMapSpecs struct { + ApproverFileEq *ebpf.MapSpec `ebpf:"approver_file_eq"` + ApproverFileHeap *ebpf.MapSpec `ebpf:"approver_file_heap"` + ApproverFilePre0 *ebpf.MapSpec `ebpf:"approver_file_pre_0"` + ApproverFilePre1 *ebpf.MapSpec `ebpf:"approver_file_pre_1"` + ApproverGen *ebpf.MapSpec `ebpf:"approver_gen"` + ApproverLpmHeap *ebpf.MapSpec `ebpf:"approver_lpm_heap"` + ApproverMode *ebpf.MapSpec `ebpf:"approver_mode"` + ApproverPid *ebpf.MapSpec `ebpf:"approver_pid"` + ApproverPort *ebpf.MapSpec `ebpf:"approver_port"` + ApproverReject *ebpf.MapSpec `ebpf:"approver_reject"` + DropCount *ebpf.MapSpec `ebpf:"drop_count"` + Enabled *ebpf.MapSpec `ebpf:"enabled"` + Events *ebpf.MapSpec `ebpf:"events"` + Scratch *ebpf.MapSpec `ebpf:"scratch"` + ScratchHeap *ebpf.MapSpec `ebpf:"scratch_heap"` +} + +// CloneVariableSpecs contains global variables before they are loaded into the kernel. +// +// It can be passed ebpf.CollectionSpec.Assign. +type CloneVariableSpecs struct { +} + +// CloneObjects contains all objects after they have been loaded into the kernel. +// +// It can be passed to LoadCloneObjects or ebpf.CollectionSpec.LoadAndAssign. +type CloneObjects struct { + ClonePrograms + CloneMaps + CloneVariables +} + +func (o *CloneObjects) Close() error { + return _CloneClose( + &o.ClonePrograms, + &o.CloneMaps, + ) +} + +// CloneMaps contains all maps after they have been loaded into the kernel. +// +// It can be passed to LoadCloneObjects or ebpf.CollectionSpec.LoadAndAssign. +type CloneMaps struct { + ApproverFileEq *ebpf.Map `ebpf:"approver_file_eq"` + ApproverFileHeap *ebpf.Map `ebpf:"approver_file_heap"` + ApproverFilePre0 *ebpf.Map `ebpf:"approver_file_pre_0"` + ApproverFilePre1 *ebpf.Map `ebpf:"approver_file_pre_1"` + ApproverGen *ebpf.Map `ebpf:"approver_gen"` + ApproverLpmHeap *ebpf.Map `ebpf:"approver_lpm_heap"` + ApproverMode *ebpf.Map `ebpf:"approver_mode"` + ApproverPid *ebpf.Map `ebpf:"approver_pid"` + ApproverPort *ebpf.Map `ebpf:"approver_port"` + ApproverReject *ebpf.Map `ebpf:"approver_reject"` + DropCount *ebpf.Map `ebpf:"drop_count"` + Enabled *ebpf.Map `ebpf:"enabled"` + Events *ebpf.Map `ebpf:"events"` + Scratch *ebpf.Map `ebpf:"scratch"` + ScratchHeap *ebpf.Map `ebpf:"scratch_heap"` +} + +func (m *CloneMaps) Close() error { + return _CloneClose( + m.ApproverFileEq, + m.ApproverFileHeap, + m.ApproverFilePre0, + m.ApproverFilePre1, + m.ApproverGen, + m.ApproverLpmHeap, + m.ApproverMode, + m.ApproverPid, + m.ApproverPort, + m.ApproverReject, + m.DropCount, + m.Enabled, + m.Events, + m.Scratch, + m.ScratchHeap, + ) +} + +// CloneVariables contains all global variables after they have been loaded into the kernel. +// +// It can be passed to LoadCloneObjects or ebpf.CollectionSpec.LoadAndAssign. +type CloneVariables struct { +} + +// ClonePrograms contains all programs after they have been loaded into the kernel. +// +// It can be passed to LoadCloneObjects or ebpf.CollectionSpec.LoadAndAssign. +type ClonePrograms struct { + HandleSchedProcessFork *ebpf.Program `ebpf:"handle_sched_process_fork"` + HandleSysEnterClone *ebpf.Program `ebpf:"handle_sys_enter_clone"` + HandleSysEnterClone3 *ebpf.Program `ebpf:"handle_sys_enter_clone3"` + HandleSysEnterFork *ebpf.Program `ebpf:"handle_sys_enter_fork"` + HandleSysEnterVfork *ebpf.Program `ebpf:"handle_sys_enter_vfork"` + HandleSysExitClone *ebpf.Program `ebpf:"handle_sys_exit_clone"` + HandleSysExitClone3 *ebpf.Program `ebpf:"handle_sys_exit_clone3"` + HandleSysExitFork *ebpf.Program `ebpf:"handle_sys_exit_fork"` + HandleSysExitVfork *ebpf.Program `ebpf:"handle_sys_exit_vfork"` +} + +func (p *ClonePrograms) Close() error { + return _CloneClose( + p.HandleSchedProcessFork, + p.HandleSysEnterClone, + p.HandleSysEnterClone3, + p.HandleSysEnterFork, + p.HandleSysEnterVfork, + p.HandleSysExitClone, + p.HandleSysExitClone3, + p.HandleSysExitFork, + p.HandleSysExitVfork, + ) +} + +func _CloneClose(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 clone_bpfeb.o +var _CloneBytes []byte diff --git a/internal/ebpf/bpf/clone_bpfeb.o b/internal/ebpf/bpf/clone_bpfeb.o new file mode 100644 index 000000000..34882e98c Binary files /dev/null and b/internal/ebpf/bpf/clone_bpfeb.o differ diff --git a/internal/ebpf/bpf/clone_bpfel.go b/internal/ebpf/bpf/clone_bpfel.go new file mode 100644 index 000000000..dcf3c9a19 --- /dev/null +++ b/internal/ebpf/bpf/clone_bpfel.go @@ -0,0 +1,241 @@ +// Code generated by bpf2go; DO NOT EDIT. +//go:build (386 || amd64 || arm || arm64 || loong64 || mips64le || mipsle || ppc64le || riscv64 || wasm) && linux + +package bpf + +import ( + "bytes" + _ "embed" + "fmt" + "io" + "structs" + + "github.com/cilium/ebpf" +) + +type CloneApproverFileKey struct { + _ structs.HostLayout + Gen uint32 + Type uint32 + Path [256]uint8 +} + +type CloneApproverLpmKey struct { + _ structs.HostLayout + Prefixlen uint32 + Path [256]uint8 +} + +type CloneApproverPidKey struct { + _ structs.HostLayout + Gen uint32 + Type uint32 + Pid uint64 +} + +type CloneApproverPortKey struct { + _ structs.HostLayout + Gen uint32 + Type uint32 + Port uint16 + Pad uint16 +} + +type CloneScratchValue struct { + _ structs.HostLayout + Arg0 uint64 + Arg1 uint64 + Arg2 uint64 + Arg3 uint64 + Flags uint64 + Truncated uint32 + Pad uint32 + Filename [256]uint8 + Aux [256]uint8 +} + +// LoadClone returns the embedded CollectionSpec for Clone. +func LoadClone() (*ebpf.CollectionSpec, error) { + reader := bytes.NewReader(_CloneBytes) + spec, err := ebpf.LoadCollectionSpecFromReader(reader) + if err != nil { + return nil, fmt.Errorf("can't load Clone: %w", err) + } + + return spec, err +} + +// LoadCloneObjects loads Clone and converts it into a struct. +// +// The following types are suitable as obj argument: +// +// *CloneObjects +// *ClonePrograms +// *CloneMaps +// +// See ebpf.CollectionSpec.LoadAndAssign documentation for details. +func LoadCloneObjects(obj interface{}, opts *ebpf.CollectionOptions) error { + spec, err := LoadClone() + if err != nil { + return err + } + + return spec.LoadAndAssign(obj, opts) +} + +// CloneSpecs contains maps and programs before they are loaded into the kernel. +// +// It can be passed ebpf.CollectionSpec.Assign. +type CloneSpecs struct { + CloneProgramSpecs + CloneMapSpecs + CloneVariableSpecs +} + +// CloneProgramSpecs contains programs before they are loaded into the kernel. +// +// It can be passed ebpf.CollectionSpec.Assign. +type CloneProgramSpecs struct { + HandleSchedProcessFork *ebpf.ProgramSpec `ebpf:"handle_sched_process_fork"` + HandleSysEnterClone *ebpf.ProgramSpec `ebpf:"handle_sys_enter_clone"` + HandleSysEnterClone3 *ebpf.ProgramSpec `ebpf:"handle_sys_enter_clone3"` + HandleSysEnterFork *ebpf.ProgramSpec `ebpf:"handle_sys_enter_fork"` + HandleSysEnterVfork *ebpf.ProgramSpec `ebpf:"handle_sys_enter_vfork"` + HandleSysExitClone *ebpf.ProgramSpec `ebpf:"handle_sys_exit_clone"` + HandleSysExitClone3 *ebpf.ProgramSpec `ebpf:"handle_sys_exit_clone3"` + HandleSysExitFork *ebpf.ProgramSpec `ebpf:"handle_sys_exit_fork"` + HandleSysExitVfork *ebpf.ProgramSpec `ebpf:"handle_sys_exit_vfork"` +} + +// CloneMapSpecs contains maps before they are loaded into the kernel. +// +// It can be passed ebpf.CollectionSpec.Assign. +type CloneMapSpecs struct { + ApproverFileEq *ebpf.MapSpec `ebpf:"approver_file_eq"` + ApproverFileHeap *ebpf.MapSpec `ebpf:"approver_file_heap"` + ApproverFilePre0 *ebpf.MapSpec `ebpf:"approver_file_pre_0"` + ApproverFilePre1 *ebpf.MapSpec `ebpf:"approver_file_pre_1"` + ApproverGen *ebpf.MapSpec `ebpf:"approver_gen"` + ApproverLpmHeap *ebpf.MapSpec `ebpf:"approver_lpm_heap"` + ApproverMode *ebpf.MapSpec `ebpf:"approver_mode"` + ApproverPid *ebpf.MapSpec `ebpf:"approver_pid"` + ApproverPort *ebpf.MapSpec `ebpf:"approver_port"` + ApproverReject *ebpf.MapSpec `ebpf:"approver_reject"` + DropCount *ebpf.MapSpec `ebpf:"drop_count"` + Enabled *ebpf.MapSpec `ebpf:"enabled"` + Events *ebpf.MapSpec `ebpf:"events"` + Scratch *ebpf.MapSpec `ebpf:"scratch"` + ScratchHeap *ebpf.MapSpec `ebpf:"scratch_heap"` +} + +// CloneVariableSpecs contains global variables before they are loaded into the kernel. +// +// It can be passed ebpf.CollectionSpec.Assign. +type CloneVariableSpecs struct { +} + +// CloneObjects contains all objects after they have been loaded into the kernel. +// +// It can be passed to LoadCloneObjects or ebpf.CollectionSpec.LoadAndAssign. +type CloneObjects struct { + ClonePrograms + CloneMaps + CloneVariables +} + +func (o *CloneObjects) Close() error { + return _CloneClose( + &o.ClonePrograms, + &o.CloneMaps, + ) +} + +// CloneMaps contains all maps after they have been loaded into the kernel. +// +// It can be passed to LoadCloneObjects or ebpf.CollectionSpec.LoadAndAssign. +type CloneMaps struct { + ApproverFileEq *ebpf.Map `ebpf:"approver_file_eq"` + ApproverFileHeap *ebpf.Map `ebpf:"approver_file_heap"` + ApproverFilePre0 *ebpf.Map `ebpf:"approver_file_pre_0"` + ApproverFilePre1 *ebpf.Map `ebpf:"approver_file_pre_1"` + ApproverGen *ebpf.Map `ebpf:"approver_gen"` + ApproverLpmHeap *ebpf.Map `ebpf:"approver_lpm_heap"` + ApproverMode *ebpf.Map `ebpf:"approver_mode"` + ApproverPid *ebpf.Map `ebpf:"approver_pid"` + ApproverPort *ebpf.Map `ebpf:"approver_port"` + ApproverReject *ebpf.Map `ebpf:"approver_reject"` + DropCount *ebpf.Map `ebpf:"drop_count"` + Enabled *ebpf.Map `ebpf:"enabled"` + Events *ebpf.Map `ebpf:"events"` + Scratch *ebpf.Map `ebpf:"scratch"` + ScratchHeap *ebpf.Map `ebpf:"scratch_heap"` +} + +func (m *CloneMaps) Close() error { + return _CloneClose( + m.ApproverFileEq, + m.ApproverFileHeap, + m.ApproverFilePre0, + m.ApproverFilePre1, + m.ApproverGen, + m.ApproverLpmHeap, + m.ApproverMode, + m.ApproverPid, + m.ApproverPort, + m.ApproverReject, + m.DropCount, + m.Enabled, + m.Events, + m.Scratch, + m.ScratchHeap, + ) +} + +// CloneVariables contains all global variables after they have been loaded into the kernel. +// +// It can be passed to LoadCloneObjects or ebpf.CollectionSpec.LoadAndAssign. +type CloneVariables struct { +} + +// ClonePrograms contains all programs after they have been loaded into the kernel. +// +// It can be passed to LoadCloneObjects or ebpf.CollectionSpec.LoadAndAssign. +type ClonePrograms struct { + HandleSchedProcessFork *ebpf.Program `ebpf:"handle_sched_process_fork"` + HandleSysEnterClone *ebpf.Program `ebpf:"handle_sys_enter_clone"` + HandleSysEnterClone3 *ebpf.Program `ebpf:"handle_sys_enter_clone3"` + HandleSysEnterFork *ebpf.Program `ebpf:"handle_sys_enter_fork"` + HandleSysEnterVfork *ebpf.Program `ebpf:"handle_sys_enter_vfork"` + HandleSysExitClone *ebpf.Program `ebpf:"handle_sys_exit_clone"` + HandleSysExitClone3 *ebpf.Program `ebpf:"handle_sys_exit_clone3"` + HandleSysExitFork *ebpf.Program `ebpf:"handle_sys_exit_fork"` + HandleSysExitVfork *ebpf.Program `ebpf:"handle_sys_exit_vfork"` +} + +func (p *ClonePrograms) Close() error { + return _CloneClose( + p.HandleSchedProcessFork, + p.HandleSysEnterClone, + p.HandleSysEnterClone3, + p.HandleSysEnterFork, + p.HandleSysEnterVfork, + p.HandleSysExitClone, + p.HandleSysExitClone3, + p.HandleSysExitFork, + p.HandleSysExitVfork, + ) +} + +func _CloneClose(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 clone_bpfel.o +var _CloneBytes []byte diff --git a/internal/ebpf/bpf/clone_bpfel.o b/internal/ebpf/bpf/clone_bpfel.o new file mode 100644 index 000000000..8d659e946 Binary files /dev/null and b/internal/ebpf/bpf/clone_bpfel.o differ diff --git a/internal/ebpf/bpf/ctl_bpfeb.go b/internal/ebpf/bpf/ctl_bpfeb.go new file mode 100644 index 000000000..4ca490886 --- /dev/null +++ b/internal/ebpf/bpf/ctl_bpfeb.go @@ -0,0 +1,217 @@ +// Code generated by bpf2go; DO NOT EDIT. +//go:build (mips || mips64 || ppc64 || s390x) && linux + +package bpf + +import ( + "bytes" + _ "embed" + "fmt" + "io" + "structs" + + "github.com/cilium/ebpf" +) + +type CtlApproverFileKey struct { + _ structs.HostLayout + Gen uint32 + Type uint32 + Path [256]uint8 +} + +type CtlApproverLpmKey struct { + _ structs.HostLayout + Prefixlen uint32 + Path [256]uint8 +} + +type CtlApproverPidKey struct { + _ structs.HostLayout + Gen uint32 + Type uint32 + Pid uint64 +} + +type CtlApproverPortKey struct { + _ structs.HostLayout + Gen uint32 + Type uint32 + Port uint16 + Pad uint16 +} + +type CtlScratchValue struct { + _ structs.HostLayout + Arg0 uint64 + Arg1 uint64 + Arg2 uint64 + Arg3 uint64 + Flags uint64 + Truncated uint32 + Pad uint32 + Filename [256]uint8 + Aux [256]uint8 +} + +// LoadCtl returns the embedded CollectionSpec for Ctl. +func LoadCtl() (*ebpf.CollectionSpec, error) { + reader := bytes.NewReader(_CtlBytes) + spec, err := ebpf.LoadCollectionSpecFromReader(reader) + if err != nil { + return nil, fmt.Errorf("can't load Ctl: %w", err) + } + + return spec, err +} + +// LoadCtlObjects loads Ctl and converts it into a struct. +// +// The following types are suitable as obj argument: +// +// *CtlObjects +// *CtlPrograms +// *CtlMaps +// +// See ebpf.CollectionSpec.LoadAndAssign documentation for details. +func LoadCtlObjects(obj interface{}, opts *ebpf.CollectionOptions) error { + spec, err := LoadCtl() + if err != nil { + return err + } + + return spec.LoadAndAssign(obj, opts) +} + +// CtlSpecs contains maps and programs before they are loaded into the kernel. +// +// It can be passed ebpf.CollectionSpec.Assign. +type CtlSpecs struct { + CtlProgramSpecs + CtlMapSpecs + CtlVariableSpecs +} + +// CtlProgramSpecs contains programs before they are loaded into the kernel. +// +// It can be passed ebpf.CollectionSpec.Assign. +type CtlProgramSpecs struct { + HandleSysExit *ebpf.ProgramSpec `ebpf:"handle_sys_exit"` +} + +// CtlMapSpecs contains maps before they are loaded into the kernel. +// +// It can be passed ebpf.CollectionSpec.Assign. +type CtlMapSpecs struct { + ApproverFileEq *ebpf.MapSpec `ebpf:"approver_file_eq"` + ApproverFileHeap *ebpf.MapSpec `ebpf:"approver_file_heap"` + ApproverFilePre0 *ebpf.MapSpec `ebpf:"approver_file_pre_0"` + ApproverFilePre1 *ebpf.MapSpec `ebpf:"approver_file_pre_1"` + ApproverGen *ebpf.MapSpec `ebpf:"approver_gen"` + ApproverLpmHeap *ebpf.MapSpec `ebpf:"approver_lpm_heap"` + ApproverMode *ebpf.MapSpec `ebpf:"approver_mode"` + ApproverPid *ebpf.MapSpec `ebpf:"approver_pid"` + ApproverPort *ebpf.MapSpec `ebpf:"approver_port"` + ApproverReject *ebpf.MapSpec `ebpf:"approver_reject"` + DropCount *ebpf.MapSpec `ebpf:"drop_count"` + Enabled *ebpf.MapSpec `ebpf:"enabled"` + Events *ebpf.MapSpec `ebpf:"events"` + Scratch *ebpf.MapSpec `ebpf:"scratch"` + ScratchHeap *ebpf.MapSpec `ebpf:"scratch_heap"` +} + +// CtlVariableSpecs contains global variables before they are loaded into the kernel. +// +// It can be passed ebpf.CollectionSpec.Assign. +type CtlVariableSpecs struct { +} + +// CtlObjects contains all objects after they have been loaded into the kernel. +// +// It can be passed to LoadCtlObjects or ebpf.CollectionSpec.LoadAndAssign. +type CtlObjects struct { + CtlPrograms + CtlMaps + CtlVariables +} + +func (o *CtlObjects) Close() error { + return _CtlClose( + &o.CtlPrograms, + &o.CtlMaps, + ) +} + +// CtlMaps contains all maps after they have been loaded into the kernel. +// +// It can be passed to LoadCtlObjects or ebpf.CollectionSpec.LoadAndAssign. +type CtlMaps struct { + ApproverFileEq *ebpf.Map `ebpf:"approver_file_eq"` + ApproverFileHeap *ebpf.Map `ebpf:"approver_file_heap"` + ApproverFilePre0 *ebpf.Map `ebpf:"approver_file_pre_0"` + ApproverFilePre1 *ebpf.Map `ebpf:"approver_file_pre_1"` + ApproverGen *ebpf.Map `ebpf:"approver_gen"` + ApproverLpmHeap *ebpf.Map `ebpf:"approver_lpm_heap"` + ApproverMode *ebpf.Map `ebpf:"approver_mode"` + ApproverPid *ebpf.Map `ebpf:"approver_pid"` + ApproverPort *ebpf.Map `ebpf:"approver_port"` + ApproverReject *ebpf.Map `ebpf:"approver_reject"` + DropCount *ebpf.Map `ebpf:"drop_count"` + Enabled *ebpf.Map `ebpf:"enabled"` + Events *ebpf.Map `ebpf:"events"` + Scratch *ebpf.Map `ebpf:"scratch"` + ScratchHeap *ebpf.Map `ebpf:"scratch_heap"` +} + +func (m *CtlMaps) Close() error { + return _CtlClose( + m.ApproverFileEq, + m.ApproverFileHeap, + m.ApproverFilePre0, + m.ApproverFilePre1, + m.ApproverGen, + m.ApproverLpmHeap, + m.ApproverMode, + m.ApproverPid, + m.ApproverPort, + m.ApproverReject, + m.DropCount, + m.Enabled, + m.Events, + m.Scratch, + m.ScratchHeap, + ) +} + +// CtlVariables contains all global variables after they have been loaded into the kernel. +// +// It can be passed to LoadCtlObjects or ebpf.CollectionSpec.LoadAndAssign. +type CtlVariables struct { +} + +// CtlPrograms contains all programs after they have been loaded into the kernel. +// +// It can be passed to LoadCtlObjects or ebpf.CollectionSpec.LoadAndAssign. +type CtlPrograms struct { + HandleSysExit *ebpf.Program `ebpf:"handle_sys_exit"` +} + +func (p *CtlPrograms) Close() error { + return _CtlClose( + p.HandleSysExit, + ) +} + +func _CtlClose(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 ctl_bpfeb.o +var _CtlBytes []byte diff --git a/internal/ebpf/bpf/ctl_bpfeb.o b/internal/ebpf/bpf/ctl_bpfeb.o new file mode 100644 index 000000000..0769585e8 Binary files /dev/null and b/internal/ebpf/bpf/ctl_bpfeb.o differ diff --git a/internal/ebpf/bpf/ctl_bpfel.go b/internal/ebpf/bpf/ctl_bpfel.go new file mode 100644 index 000000000..74590e969 --- /dev/null +++ b/internal/ebpf/bpf/ctl_bpfel.go @@ -0,0 +1,217 @@ +// Code generated by bpf2go; DO NOT EDIT. +//go:build (386 || amd64 || arm || arm64 || loong64 || mips64le || mipsle || ppc64le || riscv64 || wasm) && linux + +package bpf + +import ( + "bytes" + _ "embed" + "fmt" + "io" + "structs" + + "github.com/cilium/ebpf" +) + +type CtlApproverFileKey struct { + _ structs.HostLayout + Gen uint32 + Type uint32 + Path [256]uint8 +} + +type CtlApproverLpmKey struct { + _ structs.HostLayout + Prefixlen uint32 + Path [256]uint8 +} + +type CtlApproverPidKey struct { + _ structs.HostLayout + Gen uint32 + Type uint32 + Pid uint64 +} + +type CtlApproverPortKey struct { + _ structs.HostLayout + Gen uint32 + Type uint32 + Port uint16 + Pad uint16 +} + +type CtlScratchValue struct { + _ structs.HostLayout + Arg0 uint64 + Arg1 uint64 + Arg2 uint64 + Arg3 uint64 + Flags uint64 + Truncated uint32 + Pad uint32 + Filename [256]uint8 + Aux [256]uint8 +} + +// LoadCtl returns the embedded CollectionSpec for Ctl. +func LoadCtl() (*ebpf.CollectionSpec, error) { + reader := bytes.NewReader(_CtlBytes) + spec, err := ebpf.LoadCollectionSpecFromReader(reader) + if err != nil { + return nil, fmt.Errorf("can't load Ctl: %w", err) + } + + return spec, err +} + +// LoadCtlObjects loads Ctl and converts it into a struct. +// +// The following types are suitable as obj argument: +// +// *CtlObjects +// *CtlPrograms +// *CtlMaps +// +// See ebpf.CollectionSpec.LoadAndAssign documentation for details. +func LoadCtlObjects(obj interface{}, opts *ebpf.CollectionOptions) error { + spec, err := LoadCtl() + if err != nil { + return err + } + + return spec.LoadAndAssign(obj, opts) +} + +// CtlSpecs contains maps and programs before they are loaded into the kernel. +// +// It can be passed ebpf.CollectionSpec.Assign. +type CtlSpecs struct { + CtlProgramSpecs + CtlMapSpecs + CtlVariableSpecs +} + +// CtlProgramSpecs contains programs before they are loaded into the kernel. +// +// It can be passed ebpf.CollectionSpec.Assign. +type CtlProgramSpecs struct { + HandleSysExit *ebpf.ProgramSpec `ebpf:"handle_sys_exit"` +} + +// CtlMapSpecs contains maps before they are loaded into the kernel. +// +// It can be passed ebpf.CollectionSpec.Assign. +type CtlMapSpecs struct { + ApproverFileEq *ebpf.MapSpec `ebpf:"approver_file_eq"` + ApproverFileHeap *ebpf.MapSpec `ebpf:"approver_file_heap"` + ApproverFilePre0 *ebpf.MapSpec `ebpf:"approver_file_pre_0"` + ApproverFilePre1 *ebpf.MapSpec `ebpf:"approver_file_pre_1"` + ApproverGen *ebpf.MapSpec `ebpf:"approver_gen"` + ApproverLpmHeap *ebpf.MapSpec `ebpf:"approver_lpm_heap"` + ApproverMode *ebpf.MapSpec `ebpf:"approver_mode"` + ApproverPid *ebpf.MapSpec `ebpf:"approver_pid"` + ApproverPort *ebpf.MapSpec `ebpf:"approver_port"` + ApproverReject *ebpf.MapSpec `ebpf:"approver_reject"` + DropCount *ebpf.MapSpec `ebpf:"drop_count"` + Enabled *ebpf.MapSpec `ebpf:"enabled"` + Events *ebpf.MapSpec `ebpf:"events"` + Scratch *ebpf.MapSpec `ebpf:"scratch"` + ScratchHeap *ebpf.MapSpec `ebpf:"scratch_heap"` +} + +// CtlVariableSpecs contains global variables before they are loaded into the kernel. +// +// It can be passed ebpf.CollectionSpec.Assign. +type CtlVariableSpecs struct { +} + +// CtlObjects contains all objects after they have been loaded into the kernel. +// +// It can be passed to LoadCtlObjects or ebpf.CollectionSpec.LoadAndAssign. +type CtlObjects struct { + CtlPrograms + CtlMaps + CtlVariables +} + +func (o *CtlObjects) Close() error { + return _CtlClose( + &o.CtlPrograms, + &o.CtlMaps, + ) +} + +// CtlMaps contains all maps after they have been loaded into the kernel. +// +// It can be passed to LoadCtlObjects or ebpf.CollectionSpec.LoadAndAssign. +type CtlMaps struct { + ApproverFileEq *ebpf.Map `ebpf:"approver_file_eq"` + ApproverFileHeap *ebpf.Map `ebpf:"approver_file_heap"` + ApproverFilePre0 *ebpf.Map `ebpf:"approver_file_pre_0"` + ApproverFilePre1 *ebpf.Map `ebpf:"approver_file_pre_1"` + ApproverGen *ebpf.Map `ebpf:"approver_gen"` + ApproverLpmHeap *ebpf.Map `ebpf:"approver_lpm_heap"` + ApproverMode *ebpf.Map `ebpf:"approver_mode"` + ApproverPid *ebpf.Map `ebpf:"approver_pid"` + ApproverPort *ebpf.Map `ebpf:"approver_port"` + ApproverReject *ebpf.Map `ebpf:"approver_reject"` + DropCount *ebpf.Map `ebpf:"drop_count"` + Enabled *ebpf.Map `ebpf:"enabled"` + Events *ebpf.Map `ebpf:"events"` + Scratch *ebpf.Map `ebpf:"scratch"` + ScratchHeap *ebpf.Map `ebpf:"scratch_heap"` +} + +func (m *CtlMaps) Close() error { + return _CtlClose( + m.ApproverFileEq, + m.ApproverFileHeap, + m.ApproverFilePre0, + m.ApproverFilePre1, + m.ApproverGen, + m.ApproverLpmHeap, + m.ApproverMode, + m.ApproverPid, + m.ApproverPort, + m.ApproverReject, + m.DropCount, + m.Enabled, + m.Events, + m.Scratch, + m.ScratchHeap, + ) +} + +// CtlVariables contains all global variables after they have been loaded into the kernel. +// +// It can be passed to LoadCtlObjects or ebpf.CollectionSpec.LoadAndAssign. +type CtlVariables struct { +} + +// CtlPrograms contains all programs after they have been loaded into the kernel. +// +// It can be passed to LoadCtlObjects or ebpf.CollectionSpec.LoadAndAssign. +type CtlPrograms struct { + HandleSysExit *ebpf.Program `ebpf:"handle_sys_exit"` +} + +func (p *CtlPrograms) Close() error { + return _CtlClose( + p.HandleSysExit, + ) +} + +func _CtlClose(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 ctl_bpfel.o +var _CtlBytes []byte diff --git a/internal/ebpf/bpf/ctl_bpfel.o b/internal/ebpf/bpf/ctl_bpfel.o new file mode 100644 index 000000000..c61f26b2b Binary files /dev/null and b/internal/ebpf/bpf/ctl_bpfel.o differ diff --git a/internal/ebpf/bpf/execve_bpfeb.go b/internal/ebpf/bpf/execve_bpfeb.go new file mode 100644 index 000000000..515b4d48e --- /dev/null +++ b/internal/ebpf/bpf/execve_bpfeb.go @@ -0,0 +1,226 @@ +// Code generated by bpf2go; DO NOT EDIT. +//go:build (mips || mips64 || ppc64 || s390x) && linux + +package bpf + +import ( + "bytes" + _ "embed" + "fmt" + "io" + "structs" + + "github.com/cilium/ebpf" +) + +type ExecveApproverFileKey struct { + _ structs.HostLayout + Gen uint32 + Type uint32 + Path [256]uint8 +} + +type ExecveApproverLpmKey struct { + _ structs.HostLayout + Prefixlen uint32 + Path [256]uint8 +} + +type ExecveApproverPidKey struct { + _ structs.HostLayout + Gen uint32 + Type uint32 + Pid uint64 +} + +type ExecveApproverPortKey struct { + _ structs.HostLayout + Gen uint32 + Type uint32 + Port uint16 + Pad uint16 +} + +type ExecveScratchValue struct { + _ structs.HostLayout + Arg0 uint64 + Arg1 uint64 + Arg2 uint64 + Arg3 uint64 + Flags uint64 + Truncated uint32 + Pad uint32 + Filename [256]uint8 + Aux [256]uint8 +} + +// 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 { + HandleSysEnterExecve *ebpf.ProgramSpec `ebpf:"handle_sys_enter_execve"` + HandleSysEnterExecveat *ebpf.ProgramSpec `ebpf:"handle_sys_enter_execveat"` + HandleSysExitExecve *ebpf.ProgramSpec `ebpf:"handle_sys_exit_execve"` + HandleSysExitExecveat *ebpf.ProgramSpec `ebpf:"handle_sys_exit_execveat"` +} + +// ExecveMapSpecs contains maps before they are loaded into the kernel. +// +// It can be passed ebpf.CollectionSpec.Assign. +type ExecveMapSpecs struct { + ApproverFileEq *ebpf.MapSpec `ebpf:"approver_file_eq"` + ApproverFileHeap *ebpf.MapSpec `ebpf:"approver_file_heap"` + ApproverFilePre0 *ebpf.MapSpec `ebpf:"approver_file_pre_0"` + ApproverFilePre1 *ebpf.MapSpec `ebpf:"approver_file_pre_1"` + ApproverGen *ebpf.MapSpec `ebpf:"approver_gen"` + ApproverLpmHeap *ebpf.MapSpec `ebpf:"approver_lpm_heap"` + ApproverMode *ebpf.MapSpec `ebpf:"approver_mode"` + ApproverPid *ebpf.MapSpec `ebpf:"approver_pid"` + ApproverPort *ebpf.MapSpec `ebpf:"approver_port"` + ApproverReject *ebpf.MapSpec `ebpf:"approver_reject"` + DropCount *ebpf.MapSpec `ebpf:"drop_count"` + Enabled *ebpf.MapSpec `ebpf:"enabled"` + Events *ebpf.MapSpec `ebpf:"events"` + Scratch *ebpf.MapSpec `ebpf:"scratch"` + ScratchHeap *ebpf.MapSpec `ebpf:"scratch_heap"` +} + +// 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 { + ApproverFileEq *ebpf.Map `ebpf:"approver_file_eq"` + ApproverFileHeap *ebpf.Map `ebpf:"approver_file_heap"` + ApproverFilePre0 *ebpf.Map `ebpf:"approver_file_pre_0"` + ApproverFilePre1 *ebpf.Map `ebpf:"approver_file_pre_1"` + ApproverGen *ebpf.Map `ebpf:"approver_gen"` + ApproverLpmHeap *ebpf.Map `ebpf:"approver_lpm_heap"` + ApproverMode *ebpf.Map `ebpf:"approver_mode"` + ApproverPid *ebpf.Map `ebpf:"approver_pid"` + ApproverPort *ebpf.Map `ebpf:"approver_port"` + ApproverReject *ebpf.Map `ebpf:"approver_reject"` + DropCount *ebpf.Map `ebpf:"drop_count"` + Enabled *ebpf.Map `ebpf:"enabled"` + Events *ebpf.Map `ebpf:"events"` + Scratch *ebpf.Map `ebpf:"scratch"` + ScratchHeap *ebpf.Map `ebpf:"scratch_heap"` +} + +func (m *ExecveMaps) Close() error { + return _ExecveClose( + m.ApproverFileEq, + m.ApproverFileHeap, + m.ApproverFilePre0, + m.ApproverFilePre1, + m.ApproverGen, + m.ApproverLpmHeap, + m.ApproverMode, + m.ApproverPid, + m.ApproverPort, + m.ApproverReject, + m.DropCount, + m.Enabled, + m.Events, + m.Scratch, + m.ScratchHeap, + ) +} + +// 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 { + HandleSysEnterExecve *ebpf.Program `ebpf:"handle_sys_enter_execve"` + HandleSysEnterExecveat *ebpf.Program `ebpf:"handle_sys_enter_execveat"` + HandleSysExitExecve *ebpf.Program `ebpf:"handle_sys_exit_execve"` + HandleSysExitExecveat *ebpf.Program `ebpf:"handle_sys_exit_execveat"` +} + +func (p *ExecvePrograms) Close() error { + return _ExecveClose( + p.HandleSysEnterExecve, + p.HandleSysEnterExecveat, + p.HandleSysExitExecve, + p.HandleSysExitExecveat, + ) +} + +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/bpf/execve_bpfeb.o b/internal/ebpf/bpf/execve_bpfeb.o new file mode 100644 index 000000000..02e3398c1 Binary files /dev/null and b/internal/ebpf/bpf/execve_bpfeb.o differ diff --git a/internal/ebpf/bpf/execve_bpfel.go b/internal/ebpf/bpf/execve_bpfel.go new file mode 100644 index 000000000..d463e5a10 --- /dev/null +++ b/internal/ebpf/bpf/execve_bpfel.go @@ -0,0 +1,226 @@ +// Code generated by bpf2go; DO NOT EDIT. +//go:build (386 || amd64 || arm || arm64 || loong64 || mips64le || mipsle || ppc64le || riscv64 || wasm) && linux + +package bpf + +import ( + "bytes" + _ "embed" + "fmt" + "io" + "structs" + + "github.com/cilium/ebpf" +) + +type ExecveApproverFileKey struct { + _ structs.HostLayout + Gen uint32 + Type uint32 + Path [256]uint8 +} + +type ExecveApproverLpmKey struct { + _ structs.HostLayout + Prefixlen uint32 + Path [256]uint8 +} + +type ExecveApproverPidKey struct { + _ structs.HostLayout + Gen uint32 + Type uint32 + Pid uint64 +} + +type ExecveApproverPortKey struct { + _ structs.HostLayout + Gen uint32 + Type uint32 + Port uint16 + Pad uint16 +} + +type ExecveScratchValue struct { + _ structs.HostLayout + Arg0 uint64 + Arg1 uint64 + Arg2 uint64 + Arg3 uint64 + Flags uint64 + Truncated uint32 + Pad uint32 + Filename [256]uint8 + Aux [256]uint8 +} + +// 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 { + HandleSysEnterExecve *ebpf.ProgramSpec `ebpf:"handle_sys_enter_execve"` + HandleSysEnterExecveat *ebpf.ProgramSpec `ebpf:"handle_sys_enter_execveat"` + HandleSysExitExecve *ebpf.ProgramSpec `ebpf:"handle_sys_exit_execve"` + HandleSysExitExecveat *ebpf.ProgramSpec `ebpf:"handle_sys_exit_execveat"` +} + +// ExecveMapSpecs contains maps before they are loaded into the kernel. +// +// It can be passed ebpf.CollectionSpec.Assign. +type ExecveMapSpecs struct { + ApproverFileEq *ebpf.MapSpec `ebpf:"approver_file_eq"` + ApproverFileHeap *ebpf.MapSpec `ebpf:"approver_file_heap"` + ApproverFilePre0 *ebpf.MapSpec `ebpf:"approver_file_pre_0"` + ApproverFilePre1 *ebpf.MapSpec `ebpf:"approver_file_pre_1"` + ApproverGen *ebpf.MapSpec `ebpf:"approver_gen"` + ApproverLpmHeap *ebpf.MapSpec `ebpf:"approver_lpm_heap"` + ApproverMode *ebpf.MapSpec `ebpf:"approver_mode"` + ApproverPid *ebpf.MapSpec `ebpf:"approver_pid"` + ApproverPort *ebpf.MapSpec `ebpf:"approver_port"` + ApproverReject *ebpf.MapSpec `ebpf:"approver_reject"` + DropCount *ebpf.MapSpec `ebpf:"drop_count"` + Enabled *ebpf.MapSpec `ebpf:"enabled"` + Events *ebpf.MapSpec `ebpf:"events"` + Scratch *ebpf.MapSpec `ebpf:"scratch"` + ScratchHeap *ebpf.MapSpec `ebpf:"scratch_heap"` +} + +// 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 { + ApproverFileEq *ebpf.Map `ebpf:"approver_file_eq"` + ApproverFileHeap *ebpf.Map `ebpf:"approver_file_heap"` + ApproverFilePre0 *ebpf.Map `ebpf:"approver_file_pre_0"` + ApproverFilePre1 *ebpf.Map `ebpf:"approver_file_pre_1"` + ApproverGen *ebpf.Map `ebpf:"approver_gen"` + ApproverLpmHeap *ebpf.Map `ebpf:"approver_lpm_heap"` + ApproverMode *ebpf.Map `ebpf:"approver_mode"` + ApproverPid *ebpf.Map `ebpf:"approver_pid"` + ApproverPort *ebpf.Map `ebpf:"approver_port"` + ApproverReject *ebpf.Map `ebpf:"approver_reject"` + DropCount *ebpf.Map `ebpf:"drop_count"` + Enabled *ebpf.Map `ebpf:"enabled"` + Events *ebpf.Map `ebpf:"events"` + Scratch *ebpf.Map `ebpf:"scratch"` + ScratchHeap *ebpf.Map `ebpf:"scratch_heap"` +} + +func (m *ExecveMaps) Close() error { + return _ExecveClose( + m.ApproverFileEq, + m.ApproverFileHeap, + m.ApproverFilePre0, + m.ApproverFilePre1, + m.ApproverGen, + m.ApproverLpmHeap, + m.ApproverMode, + m.ApproverPid, + m.ApproverPort, + m.ApproverReject, + m.DropCount, + m.Enabled, + m.Events, + m.Scratch, + m.ScratchHeap, + ) +} + +// 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 { + HandleSysEnterExecve *ebpf.Program `ebpf:"handle_sys_enter_execve"` + HandleSysEnterExecveat *ebpf.Program `ebpf:"handle_sys_enter_execveat"` + HandleSysExitExecve *ebpf.Program `ebpf:"handle_sys_exit_execve"` + HandleSysExitExecveat *ebpf.Program `ebpf:"handle_sys_exit_execveat"` +} + +func (p *ExecvePrograms) Close() error { + return _ExecveClose( + p.HandleSysEnterExecve, + p.HandleSysEnterExecveat, + p.HandleSysExitExecve, + p.HandleSysExitExecveat, + ) +} + +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/bpf/execve_bpfel.o b/internal/ebpf/bpf/execve_bpfel.o new file mode 100644 index 000000000..5e46cdabc Binary files /dev/null and b/internal/ebpf/bpf/execve_bpfel.o differ diff --git a/internal/ebpf/bpf/exit_bpfeb.go b/internal/ebpf/bpf/exit_bpfeb.go new file mode 100644 index 000000000..ce9bfc931 --- /dev/null +++ b/internal/ebpf/bpf/exit_bpfeb.go @@ -0,0 +1,217 @@ +// Code generated by bpf2go; DO NOT EDIT. +//go:build (mips || mips64 || ppc64 || s390x) && linux + +package bpf + +import ( + "bytes" + _ "embed" + "fmt" + "io" + "structs" + + "github.com/cilium/ebpf" +) + +type ExitApproverFileKey struct { + _ structs.HostLayout + Gen uint32 + Type uint32 + Path [256]uint8 +} + +type ExitApproverLpmKey struct { + _ structs.HostLayout + Prefixlen uint32 + Path [256]uint8 +} + +type ExitApproverPidKey struct { + _ structs.HostLayout + Gen uint32 + Type uint32 + Pid uint64 +} + +type ExitApproverPortKey struct { + _ structs.HostLayout + Gen uint32 + Type uint32 + Port uint16 + Pad uint16 +} + +type ExitScratchValue struct { + _ structs.HostLayout + Arg0 uint64 + Arg1 uint64 + Arg2 uint64 + Arg3 uint64 + Flags uint64 + Truncated uint32 + Pad uint32 + Filename [256]uint8 + Aux [256]uint8 +} + +// LoadExit returns the embedded CollectionSpec for Exit. +func LoadExit() (*ebpf.CollectionSpec, error) { + reader := bytes.NewReader(_ExitBytes) + spec, err := ebpf.LoadCollectionSpecFromReader(reader) + if err != nil { + return nil, fmt.Errorf("can't load Exit: %w", err) + } + + return spec, err +} + +// LoadExitObjects loads Exit and converts it into a struct. +// +// The following types are suitable as obj argument: +// +// *ExitObjects +// *ExitPrograms +// *ExitMaps +// +// See ebpf.CollectionSpec.LoadAndAssign documentation for details. +func LoadExitObjects(obj interface{}, opts *ebpf.CollectionOptions) error { + spec, err := LoadExit() + if err != nil { + return err + } + + return spec.LoadAndAssign(obj, opts) +} + +// ExitSpecs contains maps and programs before they are loaded into the kernel. +// +// It can be passed ebpf.CollectionSpec.Assign. +type ExitSpecs struct { + ExitProgramSpecs + ExitMapSpecs + ExitVariableSpecs +} + +// ExitProgramSpecs contains programs before they are loaded into the kernel. +// +// It can be passed ebpf.CollectionSpec.Assign. +type ExitProgramSpecs struct { + HandleSchedProcessExit *ebpf.ProgramSpec `ebpf:"handle_sched_process_exit"` +} + +// ExitMapSpecs contains maps before they are loaded into the kernel. +// +// It can be passed ebpf.CollectionSpec.Assign. +type ExitMapSpecs struct { + ApproverFileEq *ebpf.MapSpec `ebpf:"approver_file_eq"` + ApproverFileHeap *ebpf.MapSpec `ebpf:"approver_file_heap"` + ApproverFilePre0 *ebpf.MapSpec `ebpf:"approver_file_pre_0"` + ApproverFilePre1 *ebpf.MapSpec `ebpf:"approver_file_pre_1"` + ApproverGen *ebpf.MapSpec `ebpf:"approver_gen"` + ApproverLpmHeap *ebpf.MapSpec `ebpf:"approver_lpm_heap"` + ApproverMode *ebpf.MapSpec `ebpf:"approver_mode"` + ApproverPid *ebpf.MapSpec `ebpf:"approver_pid"` + ApproverPort *ebpf.MapSpec `ebpf:"approver_port"` + ApproverReject *ebpf.MapSpec `ebpf:"approver_reject"` + DropCount *ebpf.MapSpec `ebpf:"drop_count"` + Enabled *ebpf.MapSpec `ebpf:"enabled"` + Events *ebpf.MapSpec `ebpf:"events"` + Scratch *ebpf.MapSpec `ebpf:"scratch"` + ScratchHeap *ebpf.MapSpec `ebpf:"scratch_heap"` +} + +// ExitVariableSpecs contains global variables before they are loaded into the kernel. +// +// It can be passed ebpf.CollectionSpec.Assign. +type ExitVariableSpecs struct { +} + +// ExitObjects contains all objects after they have been loaded into the kernel. +// +// It can be passed to LoadExitObjects or ebpf.CollectionSpec.LoadAndAssign. +type ExitObjects struct { + ExitPrograms + ExitMaps + ExitVariables +} + +func (o *ExitObjects) Close() error { + return _ExitClose( + &o.ExitPrograms, + &o.ExitMaps, + ) +} + +// ExitMaps contains all maps after they have been loaded into the kernel. +// +// It can be passed to LoadExitObjects or ebpf.CollectionSpec.LoadAndAssign. +type ExitMaps struct { + ApproverFileEq *ebpf.Map `ebpf:"approver_file_eq"` + ApproverFileHeap *ebpf.Map `ebpf:"approver_file_heap"` + ApproverFilePre0 *ebpf.Map `ebpf:"approver_file_pre_0"` + ApproverFilePre1 *ebpf.Map `ebpf:"approver_file_pre_1"` + ApproverGen *ebpf.Map `ebpf:"approver_gen"` + ApproverLpmHeap *ebpf.Map `ebpf:"approver_lpm_heap"` + ApproverMode *ebpf.Map `ebpf:"approver_mode"` + ApproverPid *ebpf.Map `ebpf:"approver_pid"` + ApproverPort *ebpf.Map `ebpf:"approver_port"` + ApproverReject *ebpf.Map `ebpf:"approver_reject"` + DropCount *ebpf.Map `ebpf:"drop_count"` + Enabled *ebpf.Map `ebpf:"enabled"` + Events *ebpf.Map `ebpf:"events"` + Scratch *ebpf.Map `ebpf:"scratch"` + ScratchHeap *ebpf.Map `ebpf:"scratch_heap"` +} + +func (m *ExitMaps) Close() error { + return _ExitClose( + m.ApproverFileEq, + m.ApproverFileHeap, + m.ApproverFilePre0, + m.ApproverFilePre1, + m.ApproverGen, + m.ApproverLpmHeap, + m.ApproverMode, + m.ApproverPid, + m.ApproverPort, + m.ApproverReject, + m.DropCount, + m.Enabled, + m.Events, + m.Scratch, + m.ScratchHeap, + ) +} + +// ExitVariables contains all global variables after they have been loaded into the kernel. +// +// It can be passed to LoadExitObjects or ebpf.CollectionSpec.LoadAndAssign. +type ExitVariables struct { +} + +// ExitPrograms contains all programs after they have been loaded into the kernel. +// +// It can be passed to LoadExitObjects or ebpf.CollectionSpec.LoadAndAssign. +type ExitPrograms struct { + HandleSchedProcessExit *ebpf.Program `ebpf:"handle_sched_process_exit"` +} + +func (p *ExitPrograms) Close() error { + return _ExitClose( + p.HandleSchedProcessExit, + ) +} + +func _ExitClose(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 exit_bpfeb.o +var _ExitBytes []byte diff --git a/internal/ebpf/bpf/exit_bpfeb.o b/internal/ebpf/bpf/exit_bpfeb.o new file mode 100644 index 000000000..cc57f9c81 Binary files /dev/null and b/internal/ebpf/bpf/exit_bpfeb.o differ diff --git a/internal/ebpf/bpf/exit_bpfel.go b/internal/ebpf/bpf/exit_bpfel.go new file mode 100644 index 000000000..98c83f8cd --- /dev/null +++ b/internal/ebpf/bpf/exit_bpfel.go @@ -0,0 +1,217 @@ +// Code generated by bpf2go; DO NOT EDIT. +//go:build (386 || amd64 || arm || arm64 || loong64 || mips64le || mipsle || ppc64le || riscv64 || wasm) && linux + +package bpf + +import ( + "bytes" + _ "embed" + "fmt" + "io" + "structs" + + "github.com/cilium/ebpf" +) + +type ExitApproverFileKey struct { + _ structs.HostLayout + Gen uint32 + Type uint32 + Path [256]uint8 +} + +type ExitApproverLpmKey struct { + _ structs.HostLayout + Prefixlen uint32 + Path [256]uint8 +} + +type ExitApproverPidKey struct { + _ structs.HostLayout + Gen uint32 + Type uint32 + Pid uint64 +} + +type ExitApproverPortKey struct { + _ structs.HostLayout + Gen uint32 + Type uint32 + Port uint16 + Pad uint16 +} + +type ExitScratchValue struct { + _ structs.HostLayout + Arg0 uint64 + Arg1 uint64 + Arg2 uint64 + Arg3 uint64 + Flags uint64 + Truncated uint32 + Pad uint32 + Filename [256]uint8 + Aux [256]uint8 +} + +// LoadExit returns the embedded CollectionSpec for Exit. +func LoadExit() (*ebpf.CollectionSpec, error) { + reader := bytes.NewReader(_ExitBytes) + spec, err := ebpf.LoadCollectionSpecFromReader(reader) + if err != nil { + return nil, fmt.Errorf("can't load Exit: %w", err) + } + + return spec, err +} + +// LoadExitObjects loads Exit and converts it into a struct. +// +// The following types are suitable as obj argument: +// +// *ExitObjects +// *ExitPrograms +// *ExitMaps +// +// See ebpf.CollectionSpec.LoadAndAssign documentation for details. +func LoadExitObjects(obj interface{}, opts *ebpf.CollectionOptions) error { + spec, err := LoadExit() + if err != nil { + return err + } + + return spec.LoadAndAssign(obj, opts) +} + +// ExitSpecs contains maps and programs before they are loaded into the kernel. +// +// It can be passed ebpf.CollectionSpec.Assign. +type ExitSpecs struct { + ExitProgramSpecs + ExitMapSpecs + ExitVariableSpecs +} + +// ExitProgramSpecs contains programs before they are loaded into the kernel. +// +// It can be passed ebpf.CollectionSpec.Assign. +type ExitProgramSpecs struct { + HandleSchedProcessExit *ebpf.ProgramSpec `ebpf:"handle_sched_process_exit"` +} + +// ExitMapSpecs contains maps before they are loaded into the kernel. +// +// It can be passed ebpf.CollectionSpec.Assign. +type ExitMapSpecs struct { + ApproverFileEq *ebpf.MapSpec `ebpf:"approver_file_eq"` + ApproverFileHeap *ebpf.MapSpec `ebpf:"approver_file_heap"` + ApproverFilePre0 *ebpf.MapSpec `ebpf:"approver_file_pre_0"` + ApproverFilePre1 *ebpf.MapSpec `ebpf:"approver_file_pre_1"` + ApproverGen *ebpf.MapSpec `ebpf:"approver_gen"` + ApproverLpmHeap *ebpf.MapSpec `ebpf:"approver_lpm_heap"` + ApproverMode *ebpf.MapSpec `ebpf:"approver_mode"` + ApproverPid *ebpf.MapSpec `ebpf:"approver_pid"` + ApproverPort *ebpf.MapSpec `ebpf:"approver_port"` + ApproverReject *ebpf.MapSpec `ebpf:"approver_reject"` + DropCount *ebpf.MapSpec `ebpf:"drop_count"` + Enabled *ebpf.MapSpec `ebpf:"enabled"` + Events *ebpf.MapSpec `ebpf:"events"` + Scratch *ebpf.MapSpec `ebpf:"scratch"` + ScratchHeap *ebpf.MapSpec `ebpf:"scratch_heap"` +} + +// ExitVariableSpecs contains global variables before they are loaded into the kernel. +// +// It can be passed ebpf.CollectionSpec.Assign. +type ExitVariableSpecs struct { +} + +// ExitObjects contains all objects after they have been loaded into the kernel. +// +// It can be passed to LoadExitObjects or ebpf.CollectionSpec.LoadAndAssign. +type ExitObjects struct { + ExitPrograms + ExitMaps + ExitVariables +} + +func (o *ExitObjects) Close() error { + return _ExitClose( + &o.ExitPrograms, + &o.ExitMaps, + ) +} + +// ExitMaps contains all maps after they have been loaded into the kernel. +// +// It can be passed to LoadExitObjects or ebpf.CollectionSpec.LoadAndAssign. +type ExitMaps struct { + ApproverFileEq *ebpf.Map `ebpf:"approver_file_eq"` + ApproverFileHeap *ebpf.Map `ebpf:"approver_file_heap"` + ApproverFilePre0 *ebpf.Map `ebpf:"approver_file_pre_0"` + ApproverFilePre1 *ebpf.Map `ebpf:"approver_file_pre_1"` + ApproverGen *ebpf.Map `ebpf:"approver_gen"` + ApproverLpmHeap *ebpf.Map `ebpf:"approver_lpm_heap"` + ApproverMode *ebpf.Map `ebpf:"approver_mode"` + ApproverPid *ebpf.Map `ebpf:"approver_pid"` + ApproverPort *ebpf.Map `ebpf:"approver_port"` + ApproverReject *ebpf.Map `ebpf:"approver_reject"` + DropCount *ebpf.Map `ebpf:"drop_count"` + Enabled *ebpf.Map `ebpf:"enabled"` + Events *ebpf.Map `ebpf:"events"` + Scratch *ebpf.Map `ebpf:"scratch"` + ScratchHeap *ebpf.Map `ebpf:"scratch_heap"` +} + +func (m *ExitMaps) Close() error { + return _ExitClose( + m.ApproverFileEq, + m.ApproverFileHeap, + m.ApproverFilePre0, + m.ApproverFilePre1, + m.ApproverGen, + m.ApproverLpmHeap, + m.ApproverMode, + m.ApproverPid, + m.ApproverPort, + m.ApproverReject, + m.DropCount, + m.Enabled, + m.Events, + m.Scratch, + m.ScratchHeap, + ) +} + +// ExitVariables contains all global variables after they have been loaded into the kernel. +// +// It can be passed to LoadExitObjects or ebpf.CollectionSpec.LoadAndAssign. +type ExitVariables struct { +} + +// ExitPrograms contains all programs after they have been loaded into the kernel. +// +// It can be passed to LoadExitObjects or ebpf.CollectionSpec.LoadAndAssign. +type ExitPrograms struct { + HandleSchedProcessExit *ebpf.Program `ebpf:"handle_sched_process_exit"` +} + +func (p *ExitPrograms) Close() error { + return _ExitClose( + p.HandleSchedProcessExit, + ) +} + +func _ExitClose(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 exit_bpfel.o +var _ExitBytes []byte diff --git a/internal/ebpf/bpf/exit_bpfel.o b/internal/ebpf/bpf/exit_bpfel.o new file mode 100644 index 000000000..6471cbdd2 Binary files /dev/null and b/internal/ebpf/bpf/exit_bpfel.o differ diff --git a/internal/ebpf/bpf/file_bpfeb.go b/internal/ebpf/bpf/file_bpfeb.go new file mode 100644 index 000000000..28c624010 --- /dev/null +++ b/internal/ebpf/bpf/file_bpfeb.go @@ -0,0 +1,262 @@ +// Code generated by bpf2go; DO NOT EDIT. +//go:build (mips || mips64 || ppc64 || s390x) && linux + +package bpf + +import ( + "bytes" + _ "embed" + "fmt" + "io" + "structs" + + "github.com/cilium/ebpf" +) + +type FileApproverFileKey struct { + _ structs.HostLayout + Gen uint32 + Type uint32 + Path [256]uint8 +} + +type FileApproverLpmKey struct { + _ structs.HostLayout + Prefixlen uint32 + Path [256]uint8 +} + +type FileApproverPidKey struct { + _ structs.HostLayout + Gen uint32 + Type uint32 + Pid uint64 +} + +type FileApproverPortKey struct { + _ structs.HostLayout + Gen uint32 + Type uint32 + Port uint16 + Pad uint16 +} + +type FileScratchValue struct { + _ structs.HostLayout + Arg0 uint64 + Arg1 uint64 + Arg2 uint64 + Arg3 uint64 + Flags uint64 + Truncated uint32 + Pad uint32 + Filename [256]uint8 + Aux [256]uint8 +} + +// LoadFile returns the embedded CollectionSpec for File. +func LoadFile() (*ebpf.CollectionSpec, error) { + reader := bytes.NewReader(_FileBytes) + spec, err := ebpf.LoadCollectionSpecFromReader(reader) + if err != nil { + return nil, fmt.Errorf("can't load File: %w", err) + } + + return spec, err +} + +// LoadFileObjects loads File and converts it into a struct. +// +// The following types are suitable as obj argument: +// +// *FileObjects +// *FilePrograms +// *FileMaps +// +// See ebpf.CollectionSpec.LoadAndAssign documentation for details. +func LoadFileObjects(obj interface{}, opts *ebpf.CollectionOptions) error { + spec, err := LoadFile() + if err != nil { + return err + } + + return spec.LoadAndAssign(obj, opts) +} + +// FileSpecs contains maps and programs before they are loaded into the kernel. +// +// It can be passed ebpf.CollectionSpec.Assign. +type FileSpecs struct { + FileProgramSpecs + FileMapSpecs + FileVariableSpecs +} + +// FileProgramSpecs contains programs before they are loaded into the kernel. +// +// It can be passed ebpf.CollectionSpec.Assign. +type FileProgramSpecs struct { + HandleSysEnterOpen *ebpf.ProgramSpec `ebpf:"handle_sys_enter_open"` + HandleSysEnterOpenat *ebpf.ProgramSpec `ebpf:"handle_sys_enter_openat"` + HandleSysEnterOpenat2 *ebpf.ProgramSpec `ebpf:"handle_sys_enter_openat2"` + HandleSysEnterRename *ebpf.ProgramSpec `ebpf:"handle_sys_enter_rename"` + HandleSysEnterRenameat *ebpf.ProgramSpec `ebpf:"handle_sys_enter_renameat"` + HandleSysEnterRenameat2 *ebpf.ProgramSpec `ebpf:"handle_sys_enter_renameat2"` + HandleSysEnterUnlink *ebpf.ProgramSpec `ebpf:"handle_sys_enter_unlink"` + HandleSysEnterUnlinkat *ebpf.ProgramSpec `ebpf:"handle_sys_enter_unlinkat"` + HandleSysExitOpen *ebpf.ProgramSpec `ebpf:"handle_sys_exit_open"` + HandleSysExitOpenat *ebpf.ProgramSpec `ebpf:"handle_sys_exit_openat"` + HandleSysExitOpenat2 *ebpf.ProgramSpec `ebpf:"handle_sys_exit_openat2"` + HandleSysExitRename *ebpf.ProgramSpec `ebpf:"handle_sys_exit_rename"` + HandleSysExitRenameat *ebpf.ProgramSpec `ebpf:"handle_sys_exit_renameat"` + HandleSysExitRenameat2 *ebpf.ProgramSpec `ebpf:"handle_sys_exit_renameat2"` + HandleSysExitUnlink *ebpf.ProgramSpec `ebpf:"handle_sys_exit_unlink"` + HandleSysExitUnlinkat *ebpf.ProgramSpec `ebpf:"handle_sys_exit_unlinkat"` +} + +// FileMapSpecs contains maps before they are loaded into the kernel. +// +// It can be passed ebpf.CollectionSpec.Assign. +type FileMapSpecs struct { + ApproverFileEq *ebpf.MapSpec `ebpf:"approver_file_eq"` + ApproverFileHeap *ebpf.MapSpec `ebpf:"approver_file_heap"` + ApproverFilePre0 *ebpf.MapSpec `ebpf:"approver_file_pre_0"` + ApproverFilePre1 *ebpf.MapSpec `ebpf:"approver_file_pre_1"` + ApproverGen *ebpf.MapSpec `ebpf:"approver_gen"` + ApproverLpmHeap *ebpf.MapSpec `ebpf:"approver_lpm_heap"` + ApproverMode *ebpf.MapSpec `ebpf:"approver_mode"` + ApproverPid *ebpf.MapSpec `ebpf:"approver_pid"` + ApproverPort *ebpf.MapSpec `ebpf:"approver_port"` + ApproverReject *ebpf.MapSpec `ebpf:"approver_reject"` + DropCount *ebpf.MapSpec `ebpf:"drop_count"` + Enabled *ebpf.MapSpec `ebpf:"enabled"` + Events *ebpf.MapSpec `ebpf:"events"` + Scratch *ebpf.MapSpec `ebpf:"scratch"` + ScratchHeap *ebpf.MapSpec `ebpf:"scratch_heap"` +} + +// FileVariableSpecs contains global variables before they are loaded into the kernel. +// +// It can be passed ebpf.CollectionSpec.Assign. +type FileVariableSpecs struct { +} + +// FileObjects contains all objects after they have been loaded into the kernel. +// +// It can be passed to LoadFileObjects or ebpf.CollectionSpec.LoadAndAssign. +type FileObjects struct { + FilePrograms + FileMaps + FileVariables +} + +func (o *FileObjects) Close() error { + return _FileClose( + &o.FilePrograms, + &o.FileMaps, + ) +} + +// FileMaps contains all maps after they have been loaded into the kernel. +// +// It can be passed to LoadFileObjects or ebpf.CollectionSpec.LoadAndAssign. +type FileMaps struct { + ApproverFileEq *ebpf.Map `ebpf:"approver_file_eq"` + ApproverFileHeap *ebpf.Map `ebpf:"approver_file_heap"` + ApproverFilePre0 *ebpf.Map `ebpf:"approver_file_pre_0"` + ApproverFilePre1 *ebpf.Map `ebpf:"approver_file_pre_1"` + ApproverGen *ebpf.Map `ebpf:"approver_gen"` + ApproverLpmHeap *ebpf.Map `ebpf:"approver_lpm_heap"` + ApproverMode *ebpf.Map `ebpf:"approver_mode"` + ApproverPid *ebpf.Map `ebpf:"approver_pid"` + ApproverPort *ebpf.Map `ebpf:"approver_port"` + ApproverReject *ebpf.Map `ebpf:"approver_reject"` + DropCount *ebpf.Map `ebpf:"drop_count"` + Enabled *ebpf.Map `ebpf:"enabled"` + Events *ebpf.Map `ebpf:"events"` + Scratch *ebpf.Map `ebpf:"scratch"` + ScratchHeap *ebpf.Map `ebpf:"scratch_heap"` +} + +func (m *FileMaps) Close() error { + return _FileClose( + m.ApproverFileEq, + m.ApproverFileHeap, + m.ApproverFilePre0, + m.ApproverFilePre1, + m.ApproverGen, + m.ApproverLpmHeap, + m.ApproverMode, + m.ApproverPid, + m.ApproverPort, + m.ApproverReject, + m.DropCount, + m.Enabled, + m.Events, + m.Scratch, + m.ScratchHeap, + ) +} + +// FileVariables contains all global variables after they have been loaded into the kernel. +// +// It can be passed to LoadFileObjects or ebpf.CollectionSpec.LoadAndAssign. +type FileVariables struct { +} + +// FilePrograms contains all programs after they have been loaded into the kernel. +// +// It can be passed to LoadFileObjects or ebpf.CollectionSpec.LoadAndAssign. +type FilePrograms struct { + HandleSysEnterOpen *ebpf.Program `ebpf:"handle_sys_enter_open"` + HandleSysEnterOpenat *ebpf.Program `ebpf:"handle_sys_enter_openat"` + HandleSysEnterOpenat2 *ebpf.Program `ebpf:"handle_sys_enter_openat2"` + HandleSysEnterRename *ebpf.Program `ebpf:"handle_sys_enter_rename"` + HandleSysEnterRenameat *ebpf.Program `ebpf:"handle_sys_enter_renameat"` + HandleSysEnterRenameat2 *ebpf.Program `ebpf:"handle_sys_enter_renameat2"` + HandleSysEnterUnlink *ebpf.Program `ebpf:"handle_sys_enter_unlink"` + HandleSysEnterUnlinkat *ebpf.Program `ebpf:"handle_sys_enter_unlinkat"` + HandleSysExitOpen *ebpf.Program `ebpf:"handle_sys_exit_open"` + HandleSysExitOpenat *ebpf.Program `ebpf:"handle_sys_exit_openat"` + HandleSysExitOpenat2 *ebpf.Program `ebpf:"handle_sys_exit_openat2"` + HandleSysExitRename *ebpf.Program `ebpf:"handle_sys_exit_rename"` + HandleSysExitRenameat *ebpf.Program `ebpf:"handle_sys_exit_renameat"` + HandleSysExitRenameat2 *ebpf.Program `ebpf:"handle_sys_exit_renameat2"` + HandleSysExitUnlink *ebpf.Program `ebpf:"handle_sys_exit_unlink"` + HandleSysExitUnlinkat *ebpf.Program `ebpf:"handle_sys_exit_unlinkat"` +} + +func (p *FilePrograms) Close() error { + return _FileClose( + p.HandleSysEnterOpen, + p.HandleSysEnterOpenat, + p.HandleSysEnterOpenat2, + p.HandleSysEnterRename, + p.HandleSysEnterRenameat, + p.HandleSysEnterRenameat2, + p.HandleSysEnterUnlink, + p.HandleSysEnterUnlinkat, + p.HandleSysExitOpen, + p.HandleSysExitOpenat, + p.HandleSysExitOpenat2, + p.HandleSysExitRename, + p.HandleSysExitRenameat, + p.HandleSysExitRenameat2, + p.HandleSysExitUnlink, + p.HandleSysExitUnlinkat, + ) +} + +func _FileClose(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 file_bpfeb.o +var _FileBytes []byte diff --git a/internal/ebpf/bpf/file_bpfeb.o b/internal/ebpf/bpf/file_bpfeb.o new file mode 100644 index 000000000..46747d3c1 Binary files /dev/null and b/internal/ebpf/bpf/file_bpfeb.o differ diff --git a/internal/ebpf/bpf/file_bpfel.go b/internal/ebpf/bpf/file_bpfel.go new file mode 100644 index 000000000..f66f09b8d --- /dev/null +++ b/internal/ebpf/bpf/file_bpfel.go @@ -0,0 +1,262 @@ +// Code generated by bpf2go; DO NOT EDIT. +//go:build (386 || amd64 || arm || arm64 || loong64 || mips64le || mipsle || ppc64le || riscv64 || wasm) && linux + +package bpf + +import ( + "bytes" + _ "embed" + "fmt" + "io" + "structs" + + "github.com/cilium/ebpf" +) + +type FileApproverFileKey struct { + _ structs.HostLayout + Gen uint32 + Type uint32 + Path [256]uint8 +} + +type FileApproverLpmKey struct { + _ structs.HostLayout + Prefixlen uint32 + Path [256]uint8 +} + +type FileApproverPidKey struct { + _ structs.HostLayout + Gen uint32 + Type uint32 + Pid uint64 +} + +type FileApproverPortKey struct { + _ structs.HostLayout + Gen uint32 + Type uint32 + Port uint16 + Pad uint16 +} + +type FileScratchValue struct { + _ structs.HostLayout + Arg0 uint64 + Arg1 uint64 + Arg2 uint64 + Arg3 uint64 + Flags uint64 + Truncated uint32 + Pad uint32 + Filename [256]uint8 + Aux [256]uint8 +} + +// LoadFile returns the embedded CollectionSpec for File. +func LoadFile() (*ebpf.CollectionSpec, error) { + reader := bytes.NewReader(_FileBytes) + spec, err := ebpf.LoadCollectionSpecFromReader(reader) + if err != nil { + return nil, fmt.Errorf("can't load File: %w", err) + } + + return spec, err +} + +// LoadFileObjects loads File and converts it into a struct. +// +// The following types are suitable as obj argument: +// +// *FileObjects +// *FilePrograms +// *FileMaps +// +// See ebpf.CollectionSpec.LoadAndAssign documentation for details. +func LoadFileObjects(obj interface{}, opts *ebpf.CollectionOptions) error { + spec, err := LoadFile() + if err != nil { + return err + } + + return spec.LoadAndAssign(obj, opts) +} + +// FileSpecs contains maps and programs before they are loaded into the kernel. +// +// It can be passed ebpf.CollectionSpec.Assign. +type FileSpecs struct { + FileProgramSpecs + FileMapSpecs + FileVariableSpecs +} + +// FileProgramSpecs contains programs before they are loaded into the kernel. +// +// It can be passed ebpf.CollectionSpec.Assign. +type FileProgramSpecs struct { + HandleSysEnterOpen *ebpf.ProgramSpec `ebpf:"handle_sys_enter_open"` + HandleSysEnterOpenat *ebpf.ProgramSpec `ebpf:"handle_sys_enter_openat"` + HandleSysEnterOpenat2 *ebpf.ProgramSpec `ebpf:"handle_sys_enter_openat2"` + HandleSysEnterRename *ebpf.ProgramSpec `ebpf:"handle_sys_enter_rename"` + HandleSysEnterRenameat *ebpf.ProgramSpec `ebpf:"handle_sys_enter_renameat"` + HandleSysEnterRenameat2 *ebpf.ProgramSpec `ebpf:"handle_sys_enter_renameat2"` + HandleSysEnterUnlink *ebpf.ProgramSpec `ebpf:"handle_sys_enter_unlink"` + HandleSysEnterUnlinkat *ebpf.ProgramSpec `ebpf:"handle_sys_enter_unlinkat"` + HandleSysExitOpen *ebpf.ProgramSpec `ebpf:"handle_sys_exit_open"` + HandleSysExitOpenat *ebpf.ProgramSpec `ebpf:"handle_sys_exit_openat"` + HandleSysExitOpenat2 *ebpf.ProgramSpec `ebpf:"handle_sys_exit_openat2"` + HandleSysExitRename *ebpf.ProgramSpec `ebpf:"handle_sys_exit_rename"` + HandleSysExitRenameat *ebpf.ProgramSpec `ebpf:"handle_sys_exit_renameat"` + HandleSysExitRenameat2 *ebpf.ProgramSpec `ebpf:"handle_sys_exit_renameat2"` + HandleSysExitUnlink *ebpf.ProgramSpec `ebpf:"handle_sys_exit_unlink"` + HandleSysExitUnlinkat *ebpf.ProgramSpec `ebpf:"handle_sys_exit_unlinkat"` +} + +// FileMapSpecs contains maps before they are loaded into the kernel. +// +// It can be passed ebpf.CollectionSpec.Assign. +type FileMapSpecs struct { + ApproverFileEq *ebpf.MapSpec `ebpf:"approver_file_eq"` + ApproverFileHeap *ebpf.MapSpec `ebpf:"approver_file_heap"` + ApproverFilePre0 *ebpf.MapSpec `ebpf:"approver_file_pre_0"` + ApproverFilePre1 *ebpf.MapSpec `ebpf:"approver_file_pre_1"` + ApproverGen *ebpf.MapSpec `ebpf:"approver_gen"` + ApproverLpmHeap *ebpf.MapSpec `ebpf:"approver_lpm_heap"` + ApproverMode *ebpf.MapSpec `ebpf:"approver_mode"` + ApproverPid *ebpf.MapSpec `ebpf:"approver_pid"` + ApproverPort *ebpf.MapSpec `ebpf:"approver_port"` + ApproverReject *ebpf.MapSpec `ebpf:"approver_reject"` + DropCount *ebpf.MapSpec `ebpf:"drop_count"` + Enabled *ebpf.MapSpec `ebpf:"enabled"` + Events *ebpf.MapSpec `ebpf:"events"` + Scratch *ebpf.MapSpec `ebpf:"scratch"` + ScratchHeap *ebpf.MapSpec `ebpf:"scratch_heap"` +} + +// FileVariableSpecs contains global variables before they are loaded into the kernel. +// +// It can be passed ebpf.CollectionSpec.Assign. +type FileVariableSpecs struct { +} + +// FileObjects contains all objects after they have been loaded into the kernel. +// +// It can be passed to LoadFileObjects or ebpf.CollectionSpec.LoadAndAssign. +type FileObjects struct { + FilePrograms + FileMaps + FileVariables +} + +func (o *FileObjects) Close() error { + return _FileClose( + &o.FilePrograms, + &o.FileMaps, + ) +} + +// FileMaps contains all maps after they have been loaded into the kernel. +// +// It can be passed to LoadFileObjects or ebpf.CollectionSpec.LoadAndAssign. +type FileMaps struct { + ApproverFileEq *ebpf.Map `ebpf:"approver_file_eq"` + ApproverFileHeap *ebpf.Map `ebpf:"approver_file_heap"` + ApproverFilePre0 *ebpf.Map `ebpf:"approver_file_pre_0"` + ApproverFilePre1 *ebpf.Map `ebpf:"approver_file_pre_1"` + ApproverGen *ebpf.Map `ebpf:"approver_gen"` + ApproverLpmHeap *ebpf.Map `ebpf:"approver_lpm_heap"` + ApproverMode *ebpf.Map `ebpf:"approver_mode"` + ApproverPid *ebpf.Map `ebpf:"approver_pid"` + ApproverPort *ebpf.Map `ebpf:"approver_port"` + ApproverReject *ebpf.Map `ebpf:"approver_reject"` + DropCount *ebpf.Map `ebpf:"drop_count"` + Enabled *ebpf.Map `ebpf:"enabled"` + Events *ebpf.Map `ebpf:"events"` + Scratch *ebpf.Map `ebpf:"scratch"` + ScratchHeap *ebpf.Map `ebpf:"scratch_heap"` +} + +func (m *FileMaps) Close() error { + return _FileClose( + m.ApproverFileEq, + m.ApproverFileHeap, + m.ApproverFilePre0, + m.ApproverFilePre1, + m.ApproverGen, + m.ApproverLpmHeap, + m.ApproverMode, + m.ApproverPid, + m.ApproverPort, + m.ApproverReject, + m.DropCount, + m.Enabled, + m.Events, + m.Scratch, + m.ScratchHeap, + ) +} + +// FileVariables contains all global variables after they have been loaded into the kernel. +// +// It can be passed to LoadFileObjects or ebpf.CollectionSpec.LoadAndAssign. +type FileVariables struct { +} + +// FilePrograms contains all programs after they have been loaded into the kernel. +// +// It can be passed to LoadFileObjects or ebpf.CollectionSpec.LoadAndAssign. +type FilePrograms struct { + HandleSysEnterOpen *ebpf.Program `ebpf:"handle_sys_enter_open"` + HandleSysEnterOpenat *ebpf.Program `ebpf:"handle_sys_enter_openat"` + HandleSysEnterOpenat2 *ebpf.Program `ebpf:"handle_sys_enter_openat2"` + HandleSysEnterRename *ebpf.Program `ebpf:"handle_sys_enter_rename"` + HandleSysEnterRenameat *ebpf.Program `ebpf:"handle_sys_enter_renameat"` + HandleSysEnterRenameat2 *ebpf.Program `ebpf:"handle_sys_enter_renameat2"` + HandleSysEnterUnlink *ebpf.Program `ebpf:"handle_sys_enter_unlink"` + HandleSysEnterUnlinkat *ebpf.Program `ebpf:"handle_sys_enter_unlinkat"` + HandleSysExitOpen *ebpf.Program `ebpf:"handle_sys_exit_open"` + HandleSysExitOpenat *ebpf.Program `ebpf:"handle_sys_exit_openat"` + HandleSysExitOpenat2 *ebpf.Program `ebpf:"handle_sys_exit_openat2"` + HandleSysExitRename *ebpf.Program `ebpf:"handle_sys_exit_rename"` + HandleSysExitRenameat *ebpf.Program `ebpf:"handle_sys_exit_renameat"` + HandleSysExitRenameat2 *ebpf.Program `ebpf:"handle_sys_exit_renameat2"` + HandleSysExitUnlink *ebpf.Program `ebpf:"handle_sys_exit_unlink"` + HandleSysExitUnlinkat *ebpf.Program `ebpf:"handle_sys_exit_unlinkat"` +} + +func (p *FilePrograms) Close() error { + return _FileClose( + p.HandleSysEnterOpen, + p.HandleSysEnterOpenat, + p.HandleSysEnterOpenat2, + p.HandleSysEnterRename, + p.HandleSysEnterRenameat, + p.HandleSysEnterRenameat2, + p.HandleSysEnterUnlink, + p.HandleSysEnterUnlinkat, + p.HandleSysExitOpen, + p.HandleSysExitOpenat, + p.HandleSysExitOpenat2, + p.HandleSysExitRename, + p.HandleSysExitRenameat, + p.HandleSysExitRenameat2, + p.HandleSysExitUnlink, + p.HandleSysExitUnlinkat, + ) +} + +func _FileClose(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 file_bpfel.o +var _FileBytes []byte diff --git a/internal/ebpf/bpf/file_bpfel.o b/internal/ebpf/bpf/file_bpfel.o new file mode 100644 index 000000000..610f1b10e Binary files /dev/null and b/internal/ebpf/bpf/file_bpfel.o differ diff --git a/internal/ebpf/bpf/mem_bpfeb.go b/internal/ebpf/bpf/mem_bpfeb.go new file mode 100644 index 000000000..5f8e03f39 --- /dev/null +++ b/internal/ebpf/bpf/mem_bpfeb.go @@ -0,0 +1,232 @@ +// Code generated by bpf2go; DO NOT EDIT. +//go:build (mips || mips64 || ppc64 || s390x) && linux + +package bpf + +import ( + "bytes" + _ "embed" + "fmt" + "io" + "structs" + + "github.com/cilium/ebpf" +) + +type MemApproverFileKey struct { + _ structs.HostLayout + Gen uint32 + Type uint32 + Path [256]uint8 +} + +type MemApproverLpmKey struct { + _ structs.HostLayout + Prefixlen uint32 + Path [256]uint8 +} + +type MemApproverPidKey struct { + _ structs.HostLayout + Gen uint32 + Type uint32 + Pid uint64 +} + +type MemApproverPortKey struct { + _ structs.HostLayout + Gen uint32 + Type uint32 + Port uint16 + Pad uint16 +} + +type MemScratchValue struct { + _ structs.HostLayout + Arg0 uint64 + Arg1 uint64 + Arg2 uint64 + Arg3 uint64 + Flags uint64 + Truncated uint32 + Pad uint32 + Filename [256]uint8 + Aux [256]uint8 +} + +// LoadMem returns the embedded CollectionSpec for Mem. +func LoadMem() (*ebpf.CollectionSpec, error) { + reader := bytes.NewReader(_MemBytes) + spec, err := ebpf.LoadCollectionSpecFromReader(reader) + if err != nil { + return nil, fmt.Errorf("can't load Mem: %w", err) + } + + return spec, err +} + +// LoadMemObjects loads Mem and converts it into a struct. +// +// The following types are suitable as obj argument: +// +// *MemObjects +// *MemPrograms +// *MemMaps +// +// See ebpf.CollectionSpec.LoadAndAssign documentation for details. +func LoadMemObjects(obj interface{}, opts *ebpf.CollectionOptions) error { + spec, err := LoadMem() + if err != nil { + return err + } + + return spec.LoadAndAssign(obj, opts) +} + +// MemSpecs contains maps and programs before they are loaded into the kernel. +// +// It can be passed ebpf.CollectionSpec.Assign. +type MemSpecs struct { + MemProgramSpecs + MemMapSpecs + MemVariableSpecs +} + +// MemProgramSpecs contains programs before they are loaded into the kernel. +// +// It can be passed ebpf.CollectionSpec.Assign. +type MemProgramSpecs struct { + HandleSysEnterMmap *ebpf.ProgramSpec `ebpf:"handle_sys_enter_mmap"` + HandleSysEnterProcessVmReadv *ebpf.ProgramSpec `ebpf:"handle_sys_enter_process_vm_readv"` + HandleSysEnterProcessVmWritev *ebpf.ProgramSpec `ebpf:"handle_sys_enter_process_vm_writev"` + HandleSysExitMmap *ebpf.ProgramSpec `ebpf:"handle_sys_exit_mmap"` + HandleSysExitProcessVmReadv *ebpf.ProgramSpec `ebpf:"handle_sys_exit_process_vm_readv"` + HandleSysExitProcessVmWritev *ebpf.ProgramSpec `ebpf:"handle_sys_exit_process_vm_writev"` +} + +// MemMapSpecs contains maps before they are loaded into the kernel. +// +// It can be passed ebpf.CollectionSpec.Assign. +type MemMapSpecs struct { + ApproverFileEq *ebpf.MapSpec `ebpf:"approver_file_eq"` + ApproverFileHeap *ebpf.MapSpec `ebpf:"approver_file_heap"` + ApproverFilePre0 *ebpf.MapSpec `ebpf:"approver_file_pre_0"` + ApproverFilePre1 *ebpf.MapSpec `ebpf:"approver_file_pre_1"` + ApproverGen *ebpf.MapSpec `ebpf:"approver_gen"` + ApproverLpmHeap *ebpf.MapSpec `ebpf:"approver_lpm_heap"` + ApproverMode *ebpf.MapSpec `ebpf:"approver_mode"` + ApproverPid *ebpf.MapSpec `ebpf:"approver_pid"` + ApproverPort *ebpf.MapSpec `ebpf:"approver_port"` + ApproverReject *ebpf.MapSpec `ebpf:"approver_reject"` + DropCount *ebpf.MapSpec `ebpf:"drop_count"` + Enabled *ebpf.MapSpec `ebpf:"enabled"` + Events *ebpf.MapSpec `ebpf:"events"` + Scratch *ebpf.MapSpec `ebpf:"scratch"` + ScratchHeap *ebpf.MapSpec `ebpf:"scratch_heap"` +} + +// MemVariableSpecs contains global variables before they are loaded into the kernel. +// +// It can be passed ebpf.CollectionSpec.Assign. +type MemVariableSpecs struct { +} + +// MemObjects contains all objects after they have been loaded into the kernel. +// +// It can be passed to LoadMemObjects or ebpf.CollectionSpec.LoadAndAssign. +type MemObjects struct { + MemPrograms + MemMaps + MemVariables +} + +func (o *MemObjects) Close() error { + return _MemClose( + &o.MemPrograms, + &o.MemMaps, + ) +} + +// MemMaps contains all maps after they have been loaded into the kernel. +// +// It can be passed to LoadMemObjects or ebpf.CollectionSpec.LoadAndAssign. +type MemMaps struct { + ApproverFileEq *ebpf.Map `ebpf:"approver_file_eq"` + ApproverFileHeap *ebpf.Map `ebpf:"approver_file_heap"` + ApproverFilePre0 *ebpf.Map `ebpf:"approver_file_pre_0"` + ApproverFilePre1 *ebpf.Map `ebpf:"approver_file_pre_1"` + ApproverGen *ebpf.Map `ebpf:"approver_gen"` + ApproverLpmHeap *ebpf.Map `ebpf:"approver_lpm_heap"` + ApproverMode *ebpf.Map `ebpf:"approver_mode"` + ApproverPid *ebpf.Map `ebpf:"approver_pid"` + ApproverPort *ebpf.Map `ebpf:"approver_port"` + ApproverReject *ebpf.Map `ebpf:"approver_reject"` + DropCount *ebpf.Map `ebpf:"drop_count"` + Enabled *ebpf.Map `ebpf:"enabled"` + Events *ebpf.Map `ebpf:"events"` + Scratch *ebpf.Map `ebpf:"scratch"` + ScratchHeap *ebpf.Map `ebpf:"scratch_heap"` +} + +func (m *MemMaps) Close() error { + return _MemClose( + m.ApproverFileEq, + m.ApproverFileHeap, + m.ApproverFilePre0, + m.ApproverFilePre1, + m.ApproverGen, + m.ApproverLpmHeap, + m.ApproverMode, + m.ApproverPid, + m.ApproverPort, + m.ApproverReject, + m.DropCount, + m.Enabled, + m.Events, + m.Scratch, + m.ScratchHeap, + ) +} + +// MemVariables contains all global variables after they have been loaded into the kernel. +// +// It can be passed to LoadMemObjects or ebpf.CollectionSpec.LoadAndAssign. +type MemVariables struct { +} + +// MemPrograms contains all programs after they have been loaded into the kernel. +// +// It can be passed to LoadMemObjects or ebpf.CollectionSpec.LoadAndAssign. +type MemPrograms struct { + HandleSysEnterMmap *ebpf.Program `ebpf:"handle_sys_enter_mmap"` + HandleSysEnterProcessVmReadv *ebpf.Program `ebpf:"handle_sys_enter_process_vm_readv"` + HandleSysEnterProcessVmWritev *ebpf.Program `ebpf:"handle_sys_enter_process_vm_writev"` + HandleSysExitMmap *ebpf.Program `ebpf:"handle_sys_exit_mmap"` + HandleSysExitProcessVmReadv *ebpf.Program `ebpf:"handle_sys_exit_process_vm_readv"` + HandleSysExitProcessVmWritev *ebpf.Program `ebpf:"handle_sys_exit_process_vm_writev"` +} + +func (p *MemPrograms) Close() error { + return _MemClose( + p.HandleSysEnterMmap, + p.HandleSysEnterProcessVmReadv, + p.HandleSysEnterProcessVmWritev, + p.HandleSysExitMmap, + p.HandleSysExitProcessVmReadv, + p.HandleSysExitProcessVmWritev, + ) +} + +func _MemClose(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 mem_bpfeb.o +var _MemBytes []byte diff --git a/internal/ebpf/bpf/mem_bpfeb.o b/internal/ebpf/bpf/mem_bpfeb.o new file mode 100644 index 000000000..b7514d2e1 Binary files /dev/null and b/internal/ebpf/bpf/mem_bpfeb.o differ diff --git a/internal/ebpf/bpf/mem_bpfel.go b/internal/ebpf/bpf/mem_bpfel.go new file mode 100644 index 000000000..e807e14ec --- /dev/null +++ b/internal/ebpf/bpf/mem_bpfel.go @@ -0,0 +1,232 @@ +// Code generated by bpf2go; DO NOT EDIT. +//go:build (386 || amd64 || arm || arm64 || loong64 || mips64le || mipsle || ppc64le || riscv64 || wasm) && linux + +package bpf + +import ( + "bytes" + _ "embed" + "fmt" + "io" + "structs" + + "github.com/cilium/ebpf" +) + +type MemApproverFileKey struct { + _ structs.HostLayout + Gen uint32 + Type uint32 + Path [256]uint8 +} + +type MemApproverLpmKey struct { + _ structs.HostLayout + Prefixlen uint32 + Path [256]uint8 +} + +type MemApproverPidKey struct { + _ structs.HostLayout + Gen uint32 + Type uint32 + Pid uint64 +} + +type MemApproverPortKey struct { + _ structs.HostLayout + Gen uint32 + Type uint32 + Port uint16 + Pad uint16 +} + +type MemScratchValue struct { + _ structs.HostLayout + Arg0 uint64 + Arg1 uint64 + Arg2 uint64 + Arg3 uint64 + Flags uint64 + Truncated uint32 + Pad uint32 + Filename [256]uint8 + Aux [256]uint8 +} + +// LoadMem returns the embedded CollectionSpec for Mem. +func LoadMem() (*ebpf.CollectionSpec, error) { + reader := bytes.NewReader(_MemBytes) + spec, err := ebpf.LoadCollectionSpecFromReader(reader) + if err != nil { + return nil, fmt.Errorf("can't load Mem: %w", err) + } + + return spec, err +} + +// LoadMemObjects loads Mem and converts it into a struct. +// +// The following types are suitable as obj argument: +// +// *MemObjects +// *MemPrograms +// *MemMaps +// +// See ebpf.CollectionSpec.LoadAndAssign documentation for details. +func LoadMemObjects(obj interface{}, opts *ebpf.CollectionOptions) error { + spec, err := LoadMem() + if err != nil { + return err + } + + return spec.LoadAndAssign(obj, opts) +} + +// MemSpecs contains maps and programs before they are loaded into the kernel. +// +// It can be passed ebpf.CollectionSpec.Assign. +type MemSpecs struct { + MemProgramSpecs + MemMapSpecs + MemVariableSpecs +} + +// MemProgramSpecs contains programs before they are loaded into the kernel. +// +// It can be passed ebpf.CollectionSpec.Assign. +type MemProgramSpecs struct { + HandleSysEnterMmap *ebpf.ProgramSpec `ebpf:"handle_sys_enter_mmap"` + HandleSysEnterProcessVmReadv *ebpf.ProgramSpec `ebpf:"handle_sys_enter_process_vm_readv"` + HandleSysEnterProcessVmWritev *ebpf.ProgramSpec `ebpf:"handle_sys_enter_process_vm_writev"` + HandleSysExitMmap *ebpf.ProgramSpec `ebpf:"handle_sys_exit_mmap"` + HandleSysExitProcessVmReadv *ebpf.ProgramSpec `ebpf:"handle_sys_exit_process_vm_readv"` + HandleSysExitProcessVmWritev *ebpf.ProgramSpec `ebpf:"handle_sys_exit_process_vm_writev"` +} + +// MemMapSpecs contains maps before they are loaded into the kernel. +// +// It can be passed ebpf.CollectionSpec.Assign. +type MemMapSpecs struct { + ApproverFileEq *ebpf.MapSpec `ebpf:"approver_file_eq"` + ApproverFileHeap *ebpf.MapSpec `ebpf:"approver_file_heap"` + ApproverFilePre0 *ebpf.MapSpec `ebpf:"approver_file_pre_0"` + ApproverFilePre1 *ebpf.MapSpec `ebpf:"approver_file_pre_1"` + ApproverGen *ebpf.MapSpec `ebpf:"approver_gen"` + ApproverLpmHeap *ebpf.MapSpec `ebpf:"approver_lpm_heap"` + ApproverMode *ebpf.MapSpec `ebpf:"approver_mode"` + ApproverPid *ebpf.MapSpec `ebpf:"approver_pid"` + ApproverPort *ebpf.MapSpec `ebpf:"approver_port"` + ApproverReject *ebpf.MapSpec `ebpf:"approver_reject"` + DropCount *ebpf.MapSpec `ebpf:"drop_count"` + Enabled *ebpf.MapSpec `ebpf:"enabled"` + Events *ebpf.MapSpec `ebpf:"events"` + Scratch *ebpf.MapSpec `ebpf:"scratch"` + ScratchHeap *ebpf.MapSpec `ebpf:"scratch_heap"` +} + +// MemVariableSpecs contains global variables before they are loaded into the kernel. +// +// It can be passed ebpf.CollectionSpec.Assign. +type MemVariableSpecs struct { +} + +// MemObjects contains all objects after they have been loaded into the kernel. +// +// It can be passed to LoadMemObjects or ebpf.CollectionSpec.LoadAndAssign. +type MemObjects struct { + MemPrograms + MemMaps + MemVariables +} + +func (o *MemObjects) Close() error { + return _MemClose( + &o.MemPrograms, + &o.MemMaps, + ) +} + +// MemMaps contains all maps after they have been loaded into the kernel. +// +// It can be passed to LoadMemObjects or ebpf.CollectionSpec.LoadAndAssign. +type MemMaps struct { + ApproverFileEq *ebpf.Map `ebpf:"approver_file_eq"` + ApproverFileHeap *ebpf.Map `ebpf:"approver_file_heap"` + ApproverFilePre0 *ebpf.Map `ebpf:"approver_file_pre_0"` + ApproverFilePre1 *ebpf.Map `ebpf:"approver_file_pre_1"` + ApproverGen *ebpf.Map `ebpf:"approver_gen"` + ApproverLpmHeap *ebpf.Map `ebpf:"approver_lpm_heap"` + ApproverMode *ebpf.Map `ebpf:"approver_mode"` + ApproverPid *ebpf.Map `ebpf:"approver_pid"` + ApproverPort *ebpf.Map `ebpf:"approver_port"` + ApproverReject *ebpf.Map `ebpf:"approver_reject"` + DropCount *ebpf.Map `ebpf:"drop_count"` + Enabled *ebpf.Map `ebpf:"enabled"` + Events *ebpf.Map `ebpf:"events"` + Scratch *ebpf.Map `ebpf:"scratch"` + ScratchHeap *ebpf.Map `ebpf:"scratch_heap"` +} + +func (m *MemMaps) Close() error { + return _MemClose( + m.ApproverFileEq, + m.ApproverFileHeap, + m.ApproverFilePre0, + m.ApproverFilePre1, + m.ApproverGen, + m.ApproverLpmHeap, + m.ApproverMode, + m.ApproverPid, + m.ApproverPort, + m.ApproverReject, + m.DropCount, + m.Enabled, + m.Events, + m.Scratch, + m.ScratchHeap, + ) +} + +// MemVariables contains all global variables after they have been loaded into the kernel. +// +// It can be passed to LoadMemObjects or ebpf.CollectionSpec.LoadAndAssign. +type MemVariables struct { +} + +// MemPrograms contains all programs after they have been loaded into the kernel. +// +// It can be passed to LoadMemObjects or ebpf.CollectionSpec.LoadAndAssign. +type MemPrograms struct { + HandleSysEnterMmap *ebpf.Program `ebpf:"handle_sys_enter_mmap"` + HandleSysEnterProcessVmReadv *ebpf.Program `ebpf:"handle_sys_enter_process_vm_readv"` + HandleSysEnterProcessVmWritev *ebpf.Program `ebpf:"handle_sys_enter_process_vm_writev"` + HandleSysExitMmap *ebpf.Program `ebpf:"handle_sys_exit_mmap"` + HandleSysExitProcessVmReadv *ebpf.Program `ebpf:"handle_sys_exit_process_vm_readv"` + HandleSysExitProcessVmWritev *ebpf.Program `ebpf:"handle_sys_exit_process_vm_writev"` +} + +func (p *MemPrograms) Close() error { + return _MemClose( + p.HandleSysEnterMmap, + p.HandleSysEnterProcessVmReadv, + p.HandleSysEnterProcessVmWritev, + p.HandleSysExitMmap, + p.HandleSysExitProcessVmReadv, + p.HandleSysExitProcessVmWritev, + ) +} + +func _MemClose(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 mem_bpfel.o +var _MemBytes []byte diff --git a/internal/ebpf/bpf/mem_bpfel.o b/internal/ebpf/bpf/mem_bpfel.o new file mode 100644 index 000000000..dae3f656b Binary files /dev/null and b/internal/ebpf/bpf/mem_bpfel.o differ diff --git a/internal/ebpf/bpf/net_bpfeb.go b/internal/ebpf/bpf/net_bpfeb.go new file mode 100644 index 000000000..c83567465 --- /dev/null +++ b/internal/ebpf/bpf/net_bpfeb.go @@ -0,0 +1,232 @@ +// Code generated by bpf2go; DO NOT EDIT. +//go:build (mips || mips64 || ppc64 || s390x) && linux + +package bpf + +import ( + "bytes" + _ "embed" + "fmt" + "io" + "structs" + + "github.com/cilium/ebpf" +) + +type NetApproverFileKey struct { + _ structs.HostLayout + Gen uint32 + Type uint32 + Path [256]uint8 +} + +type NetApproverLpmKey struct { + _ structs.HostLayout + Prefixlen uint32 + Path [256]uint8 +} + +type NetApproverPidKey struct { + _ structs.HostLayout + Gen uint32 + Type uint32 + Pid uint64 +} + +type NetApproverPortKey struct { + _ structs.HostLayout + Gen uint32 + Type uint32 + Port uint16 + Pad uint16 +} + +type NetScratchValue struct { + _ structs.HostLayout + Arg0 uint64 + Arg1 uint64 + Arg2 uint64 + Arg3 uint64 + Flags uint64 + Truncated uint32 + Pad uint32 + Filename [256]uint8 + Aux [256]uint8 +} + +// LoadNet returns the embedded CollectionSpec for Net. +func LoadNet() (*ebpf.CollectionSpec, error) { + reader := bytes.NewReader(_NetBytes) + spec, err := ebpf.LoadCollectionSpecFromReader(reader) + if err != nil { + return nil, fmt.Errorf("can't load Net: %w", err) + } + + return spec, err +} + +// LoadNetObjects loads Net and converts it into a struct. +// +// The following types are suitable as obj argument: +// +// *NetObjects +// *NetPrograms +// *NetMaps +// +// See ebpf.CollectionSpec.LoadAndAssign documentation for details. +func LoadNetObjects(obj interface{}, opts *ebpf.CollectionOptions) error { + spec, err := LoadNet() + if err != nil { + return err + } + + return spec.LoadAndAssign(obj, opts) +} + +// NetSpecs contains maps and programs before they are loaded into the kernel. +// +// It can be passed ebpf.CollectionSpec.Assign. +type NetSpecs struct { + NetProgramSpecs + NetMapSpecs + NetVariableSpecs +} + +// NetProgramSpecs contains programs before they are loaded into the kernel. +// +// It can be passed ebpf.CollectionSpec.Assign. +type NetProgramSpecs struct { + HandleSysEnterAccept *ebpf.ProgramSpec `ebpf:"handle_sys_enter_accept"` + HandleSysEnterAccept4 *ebpf.ProgramSpec `ebpf:"handle_sys_enter_accept4"` + HandleSysEnterConnect *ebpf.ProgramSpec `ebpf:"handle_sys_enter_connect"` + HandleSysExitAccept *ebpf.ProgramSpec `ebpf:"handle_sys_exit_accept"` + HandleSysExitAccept4 *ebpf.ProgramSpec `ebpf:"handle_sys_exit_accept4"` + HandleSysExitConnect *ebpf.ProgramSpec `ebpf:"handle_sys_exit_connect"` +} + +// NetMapSpecs contains maps before they are loaded into the kernel. +// +// It can be passed ebpf.CollectionSpec.Assign. +type NetMapSpecs struct { + ApproverFileEq *ebpf.MapSpec `ebpf:"approver_file_eq"` + ApproverFileHeap *ebpf.MapSpec `ebpf:"approver_file_heap"` + ApproverFilePre0 *ebpf.MapSpec `ebpf:"approver_file_pre_0"` + ApproverFilePre1 *ebpf.MapSpec `ebpf:"approver_file_pre_1"` + ApproverGen *ebpf.MapSpec `ebpf:"approver_gen"` + ApproverLpmHeap *ebpf.MapSpec `ebpf:"approver_lpm_heap"` + ApproverMode *ebpf.MapSpec `ebpf:"approver_mode"` + ApproverPid *ebpf.MapSpec `ebpf:"approver_pid"` + ApproverPort *ebpf.MapSpec `ebpf:"approver_port"` + ApproverReject *ebpf.MapSpec `ebpf:"approver_reject"` + DropCount *ebpf.MapSpec `ebpf:"drop_count"` + Enabled *ebpf.MapSpec `ebpf:"enabled"` + Events *ebpf.MapSpec `ebpf:"events"` + Scratch *ebpf.MapSpec `ebpf:"scratch"` + ScratchHeap *ebpf.MapSpec `ebpf:"scratch_heap"` +} + +// NetVariableSpecs contains global variables before they are loaded into the kernel. +// +// It can be passed ebpf.CollectionSpec.Assign. +type NetVariableSpecs struct { +} + +// NetObjects contains all objects after they have been loaded into the kernel. +// +// It can be passed to LoadNetObjects or ebpf.CollectionSpec.LoadAndAssign. +type NetObjects struct { + NetPrograms + NetMaps + NetVariables +} + +func (o *NetObjects) Close() error { + return _NetClose( + &o.NetPrograms, + &o.NetMaps, + ) +} + +// NetMaps contains all maps after they have been loaded into the kernel. +// +// It can be passed to LoadNetObjects or ebpf.CollectionSpec.LoadAndAssign. +type NetMaps struct { + ApproverFileEq *ebpf.Map `ebpf:"approver_file_eq"` + ApproverFileHeap *ebpf.Map `ebpf:"approver_file_heap"` + ApproverFilePre0 *ebpf.Map `ebpf:"approver_file_pre_0"` + ApproverFilePre1 *ebpf.Map `ebpf:"approver_file_pre_1"` + ApproverGen *ebpf.Map `ebpf:"approver_gen"` + ApproverLpmHeap *ebpf.Map `ebpf:"approver_lpm_heap"` + ApproverMode *ebpf.Map `ebpf:"approver_mode"` + ApproverPid *ebpf.Map `ebpf:"approver_pid"` + ApproverPort *ebpf.Map `ebpf:"approver_port"` + ApproverReject *ebpf.Map `ebpf:"approver_reject"` + DropCount *ebpf.Map `ebpf:"drop_count"` + Enabled *ebpf.Map `ebpf:"enabled"` + Events *ebpf.Map `ebpf:"events"` + Scratch *ebpf.Map `ebpf:"scratch"` + ScratchHeap *ebpf.Map `ebpf:"scratch_heap"` +} + +func (m *NetMaps) Close() error { + return _NetClose( + m.ApproverFileEq, + m.ApproverFileHeap, + m.ApproverFilePre0, + m.ApproverFilePre1, + m.ApproverGen, + m.ApproverLpmHeap, + m.ApproverMode, + m.ApproverPid, + m.ApproverPort, + m.ApproverReject, + m.DropCount, + m.Enabled, + m.Events, + m.Scratch, + m.ScratchHeap, + ) +} + +// NetVariables contains all global variables after they have been loaded into the kernel. +// +// It can be passed to LoadNetObjects or ebpf.CollectionSpec.LoadAndAssign. +type NetVariables struct { +} + +// NetPrograms contains all programs after they have been loaded into the kernel. +// +// It can be passed to LoadNetObjects or ebpf.CollectionSpec.LoadAndAssign. +type NetPrograms struct { + HandleSysEnterAccept *ebpf.Program `ebpf:"handle_sys_enter_accept"` + HandleSysEnterAccept4 *ebpf.Program `ebpf:"handle_sys_enter_accept4"` + HandleSysEnterConnect *ebpf.Program `ebpf:"handle_sys_enter_connect"` + HandleSysExitAccept *ebpf.Program `ebpf:"handle_sys_exit_accept"` + HandleSysExitAccept4 *ebpf.Program `ebpf:"handle_sys_exit_accept4"` + HandleSysExitConnect *ebpf.Program `ebpf:"handle_sys_exit_connect"` +} + +func (p *NetPrograms) Close() error { + return _NetClose( + p.HandleSysEnterAccept, + p.HandleSysEnterAccept4, + p.HandleSysEnterConnect, + p.HandleSysExitAccept, + p.HandleSysExitAccept4, + p.HandleSysExitConnect, + ) +} + +func _NetClose(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 net_bpfeb.o +var _NetBytes []byte diff --git a/internal/ebpf/bpf/net_bpfeb.o b/internal/ebpf/bpf/net_bpfeb.o new file mode 100644 index 000000000..e8851dbd5 Binary files /dev/null and b/internal/ebpf/bpf/net_bpfeb.o differ diff --git a/internal/ebpf/bpf/net_bpfel.go b/internal/ebpf/bpf/net_bpfel.go new file mode 100644 index 000000000..8e87c33a6 --- /dev/null +++ b/internal/ebpf/bpf/net_bpfel.go @@ -0,0 +1,232 @@ +// Code generated by bpf2go; DO NOT EDIT. +//go:build (386 || amd64 || arm || arm64 || loong64 || mips64le || mipsle || ppc64le || riscv64 || wasm) && linux + +package bpf + +import ( + "bytes" + _ "embed" + "fmt" + "io" + "structs" + + "github.com/cilium/ebpf" +) + +type NetApproverFileKey struct { + _ structs.HostLayout + Gen uint32 + Type uint32 + Path [256]uint8 +} + +type NetApproverLpmKey struct { + _ structs.HostLayout + Prefixlen uint32 + Path [256]uint8 +} + +type NetApproverPidKey struct { + _ structs.HostLayout + Gen uint32 + Type uint32 + Pid uint64 +} + +type NetApproverPortKey struct { + _ structs.HostLayout + Gen uint32 + Type uint32 + Port uint16 + Pad uint16 +} + +type NetScratchValue struct { + _ structs.HostLayout + Arg0 uint64 + Arg1 uint64 + Arg2 uint64 + Arg3 uint64 + Flags uint64 + Truncated uint32 + Pad uint32 + Filename [256]uint8 + Aux [256]uint8 +} + +// LoadNet returns the embedded CollectionSpec for Net. +func LoadNet() (*ebpf.CollectionSpec, error) { + reader := bytes.NewReader(_NetBytes) + spec, err := ebpf.LoadCollectionSpecFromReader(reader) + if err != nil { + return nil, fmt.Errorf("can't load Net: %w", err) + } + + return spec, err +} + +// LoadNetObjects loads Net and converts it into a struct. +// +// The following types are suitable as obj argument: +// +// *NetObjects +// *NetPrograms +// *NetMaps +// +// See ebpf.CollectionSpec.LoadAndAssign documentation for details. +func LoadNetObjects(obj interface{}, opts *ebpf.CollectionOptions) error { + spec, err := LoadNet() + if err != nil { + return err + } + + return spec.LoadAndAssign(obj, opts) +} + +// NetSpecs contains maps and programs before they are loaded into the kernel. +// +// It can be passed ebpf.CollectionSpec.Assign. +type NetSpecs struct { + NetProgramSpecs + NetMapSpecs + NetVariableSpecs +} + +// NetProgramSpecs contains programs before they are loaded into the kernel. +// +// It can be passed ebpf.CollectionSpec.Assign. +type NetProgramSpecs struct { + HandleSysEnterAccept *ebpf.ProgramSpec `ebpf:"handle_sys_enter_accept"` + HandleSysEnterAccept4 *ebpf.ProgramSpec `ebpf:"handle_sys_enter_accept4"` + HandleSysEnterConnect *ebpf.ProgramSpec `ebpf:"handle_sys_enter_connect"` + HandleSysExitAccept *ebpf.ProgramSpec `ebpf:"handle_sys_exit_accept"` + HandleSysExitAccept4 *ebpf.ProgramSpec `ebpf:"handle_sys_exit_accept4"` + HandleSysExitConnect *ebpf.ProgramSpec `ebpf:"handle_sys_exit_connect"` +} + +// NetMapSpecs contains maps before they are loaded into the kernel. +// +// It can be passed ebpf.CollectionSpec.Assign. +type NetMapSpecs struct { + ApproverFileEq *ebpf.MapSpec `ebpf:"approver_file_eq"` + ApproverFileHeap *ebpf.MapSpec `ebpf:"approver_file_heap"` + ApproverFilePre0 *ebpf.MapSpec `ebpf:"approver_file_pre_0"` + ApproverFilePre1 *ebpf.MapSpec `ebpf:"approver_file_pre_1"` + ApproverGen *ebpf.MapSpec `ebpf:"approver_gen"` + ApproverLpmHeap *ebpf.MapSpec `ebpf:"approver_lpm_heap"` + ApproverMode *ebpf.MapSpec `ebpf:"approver_mode"` + ApproverPid *ebpf.MapSpec `ebpf:"approver_pid"` + ApproverPort *ebpf.MapSpec `ebpf:"approver_port"` + ApproverReject *ebpf.MapSpec `ebpf:"approver_reject"` + DropCount *ebpf.MapSpec `ebpf:"drop_count"` + Enabled *ebpf.MapSpec `ebpf:"enabled"` + Events *ebpf.MapSpec `ebpf:"events"` + Scratch *ebpf.MapSpec `ebpf:"scratch"` + ScratchHeap *ebpf.MapSpec `ebpf:"scratch_heap"` +} + +// NetVariableSpecs contains global variables before they are loaded into the kernel. +// +// It can be passed ebpf.CollectionSpec.Assign. +type NetVariableSpecs struct { +} + +// NetObjects contains all objects after they have been loaded into the kernel. +// +// It can be passed to LoadNetObjects or ebpf.CollectionSpec.LoadAndAssign. +type NetObjects struct { + NetPrograms + NetMaps + NetVariables +} + +func (o *NetObjects) Close() error { + return _NetClose( + &o.NetPrograms, + &o.NetMaps, + ) +} + +// NetMaps contains all maps after they have been loaded into the kernel. +// +// It can be passed to LoadNetObjects or ebpf.CollectionSpec.LoadAndAssign. +type NetMaps struct { + ApproverFileEq *ebpf.Map `ebpf:"approver_file_eq"` + ApproverFileHeap *ebpf.Map `ebpf:"approver_file_heap"` + ApproverFilePre0 *ebpf.Map `ebpf:"approver_file_pre_0"` + ApproverFilePre1 *ebpf.Map `ebpf:"approver_file_pre_1"` + ApproverGen *ebpf.Map `ebpf:"approver_gen"` + ApproverLpmHeap *ebpf.Map `ebpf:"approver_lpm_heap"` + ApproverMode *ebpf.Map `ebpf:"approver_mode"` + ApproverPid *ebpf.Map `ebpf:"approver_pid"` + ApproverPort *ebpf.Map `ebpf:"approver_port"` + ApproverReject *ebpf.Map `ebpf:"approver_reject"` + DropCount *ebpf.Map `ebpf:"drop_count"` + Enabled *ebpf.Map `ebpf:"enabled"` + Events *ebpf.Map `ebpf:"events"` + Scratch *ebpf.Map `ebpf:"scratch"` + ScratchHeap *ebpf.Map `ebpf:"scratch_heap"` +} + +func (m *NetMaps) Close() error { + return _NetClose( + m.ApproverFileEq, + m.ApproverFileHeap, + m.ApproverFilePre0, + m.ApproverFilePre1, + m.ApproverGen, + m.ApproverLpmHeap, + m.ApproverMode, + m.ApproverPid, + m.ApproverPort, + m.ApproverReject, + m.DropCount, + m.Enabled, + m.Events, + m.Scratch, + m.ScratchHeap, + ) +} + +// NetVariables contains all global variables after they have been loaded into the kernel. +// +// It can be passed to LoadNetObjects or ebpf.CollectionSpec.LoadAndAssign. +type NetVariables struct { +} + +// NetPrograms contains all programs after they have been loaded into the kernel. +// +// It can be passed to LoadNetObjects or ebpf.CollectionSpec.LoadAndAssign. +type NetPrograms struct { + HandleSysEnterAccept *ebpf.Program `ebpf:"handle_sys_enter_accept"` + HandleSysEnterAccept4 *ebpf.Program `ebpf:"handle_sys_enter_accept4"` + HandleSysEnterConnect *ebpf.Program `ebpf:"handle_sys_enter_connect"` + HandleSysExitAccept *ebpf.Program `ebpf:"handle_sys_exit_accept"` + HandleSysExitAccept4 *ebpf.Program `ebpf:"handle_sys_exit_accept4"` + HandleSysExitConnect *ebpf.Program `ebpf:"handle_sys_exit_connect"` +} + +func (p *NetPrograms) Close() error { + return _NetClose( + p.HandleSysEnterAccept, + p.HandleSysEnterAccept4, + p.HandleSysEnterConnect, + p.HandleSysExitAccept, + p.HandleSysExitAccept4, + p.HandleSysExitConnect, + ) +} + +func _NetClose(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 net_bpfel.o +var _NetBytes []byte diff --git a/internal/ebpf/bpf/net_bpfel.o b/internal/ebpf/bpf/net_bpfel.o new file mode 100644 index 000000000..9b8be1756 Binary files /dev/null and b/internal/ebpf/bpf/net_bpfel.o differ diff --git a/internal/ebpf/bpf/prociter_bpfeb.go b/internal/ebpf/bpf/prociter_bpfeb.go new file mode 100644 index 000000000..7c35590d7 --- /dev/null +++ b/internal/ebpf/bpf/prociter_bpfeb.go @@ -0,0 +1,217 @@ +// Code generated by bpf2go; DO NOT EDIT. +//go:build (mips || mips64 || ppc64 || s390x) && linux + +package bpf + +import ( + "bytes" + _ "embed" + "fmt" + "io" + "structs" + + "github.com/cilium/ebpf" +) + +type ProciterApproverFileKey struct { + _ structs.HostLayout + Gen uint32 + Type uint32 + Path [256]uint8 +} + +type ProciterApproverLpmKey struct { + _ structs.HostLayout + Prefixlen uint32 + Path [256]uint8 +} + +type ProciterApproverPidKey struct { + _ structs.HostLayout + Gen uint32 + Type uint32 + Pid uint64 +} + +type ProciterApproverPortKey struct { + _ structs.HostLayout + Gen uint32 + Type uint32 + Port uint16 + Pad uint16 +} + +type ProciterScratchValue struct { + _ structs.HostLayout + Arg0 uint64 + Arg1 uint64 + Arg2 uint64 + Arg3 uint64 + Flags uint64 + Truncated uint32 + Pad uint32 + Filename [256]uint8 + Aux [256]uint8 +} + +// 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 { + ApproverFileEq *ebpf.MapSpec `ebpf:"approver_file_eq"` + ApproverFileHeap *ebpf.MapSpec `ebpf:"approver_file_heap"` + ApproverFilePre0 *ebpf.MapSpec `ebpf:"approver_file_pre_0"` + ApproverFilePre1 *ebpf.MapSpec `ebpf:"approver_file_pre_1"` + ApproverGen *ebpf.MapSpec `ebpf:"approver_gen"` + ApproverLpmHeap *ebpf.MapSpec `ebpf:"approver_lpm_heap"` + ApproverMode *ebpf.MapSpec `ebpf:"approver_mode"` + ApproverPid *ebpf.MapSpec `ebpf:"approver_pid"` + ApproverPort *ebpf.MapSpec `ebpf:"approver_port"` + ApproverReject *ebpf.MapSpec `ebpf:"approver_reject"` + DropCount *ebpf.MapSpec `ebpf:"drop_count"` + Enabled *ebpf.MapSpec `ebpf:"enabled"` + Events *ebpf.MapSpec `ebpf:"events"` + Scratch *ebpf.MapSpec `ebpf:"scratch"` + ScratchHeap *ebpf.MapSpec `ebpf:"scratch_heap"` +} + +// 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 { + ApproverFileEq *ebpf.Map `ebpf:"approver_file_eq"` + ApproverFileHeap *ebpf.Map `ebpf:"approver_file_heap"` + ApproverFilePre0 *ebpf.Map `ebpf:"approver_file_pre_0"` + ApproverFilePre1 *ebpf.Map `ebpf:"approver_file_pre_1"` + ApproverGen *ebpf.Map `ebpf:"approver_gen"` + ApproverLpmHeap *ebpf.Map `ebpf:"approver_lpm_heap"` + ApproverMode *ebpf.Map `ebpf:"approver_mode"` + ApproverPid *ebpf.Map `ebpf:"approver_pid"` + ApproverPort *ebpf.Map `ebpf:"approver_port"` + ApproverReject *ebpf.Map `ebpf:"approver_reject"` + DropCount *ebpf.Map `ebpf:"drop_count"` + Enabled *ebpf.Map `ebpf:"enabled"` + Events *ebpf.Map `ebpf:"events"` + Scratch *ebpf.Map `ebpf:"scratch"` + ScratchHeap *ebpf.Map `ebpf:"scratch_heap"` +} + +func (m *ProciterMaps) Close() error { + return _ProciterClose( + m.ApproverFileEq, + m.ApproverFileHeap, + m.ApproverFilePre0, + m.ApproverFilePre1, + m.ApproverGen, + m.ApproverLpmHeap, + m.ApproverMode, + m.ApproverPid, + m.ApproverPort, + m.ApproverReject, + m.DropCount, + m.Enabled, + m.Events, + m.Scratch, + m.ScratchHeap, + ) +} + +// 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/bpf/prociter_bpfeb.o b/internal/ebpf/bpf/prociter_bpfeb.o new file mode 100644 index 000000000..541573a5d Binary files /dev/null and b/internal/ebpf/bpf/prociter_bpfeb.o differ diff --git a/internal/ebpf/bpf/prociter_bpfel.go b/internal/ebpf/bpf/prociter_bpfel.go new file mode 100644 index 000000000..fada2c274 --- /dev/null +++ b/internal/ebpf/bpf/prociter_bpfel.go @@ -0,0 +1,217 @@ +// Code generated by bpf2go; DO NOT EDIT. +//go:build (386 || amd64 || arm || arm64 || loong64 || mips64le || mipsle || ppc64le || riscv64 || wasm) && linux + +package bpf + +import ( + "bytes" + _ "embed" + "fmt" + "io" + "structs" + + "github.com/cilium/ebpf" +) + +type ProciterApproverFileKey struct { + _ structs.HostLayout + Gen uint32 + Type uint32 + Path [256]uint8 +} + +type ProciterApproverLpmKey struct { + _ structs.HostLayout + Prefixlen uint32 + Path [256]uint8 +} + +type ProciterApproverPidKey struct { + _ structs.HostLayout + Gen uint32 + Type uint32 + Pid uint64 +} + +type ProciterApproverPortKey struct { + _ structs.HostLayout + Gen uint32 + Type uint32 + Port uint16 + Pad uint16 +} + +type ProciterScratchValue struct { + _ structs.HostLayout + Arg0 uint64 + Arg1 uint64 + Arg2 uint64 + Arg3 uint64 + Flags uint64 + Truncated uint32 + Pad uint32 + Filename [256]uint8 + Aux [256]uint8 +} + +// 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 { + ApproverFileEq *ebpf.MapSpec `ebpf:"approver_file_eq"` + ApproverFileHeap *ebpf.MapSpec `ebpf:"approver_file_heap"` + ApproverFilePre0 *ebpf.MapSpec `ebpf:"approver_file_pre_0"` + ApproverFilePre1 *ebpf.MapSpec `ebpf:"approver_file_pre_1"` + ApproverGen *ebpf.MapSpec `ebpf:"approver_gen"` + ApproverLpmHeap *ebpf.MapSpec `ebpf:"approver_lpm_heap"` + ApproverMode *ebpf.MapSpec `ebpf:"approver_mode"` + ApproverPid *ebpf.MapSpec `ebpf:"approver_pid"` + ApproverPort *ebpf.MapSpec `ebpf:"approver_port"` + ApproverReject *ebpf.MapSpec `ebpf:"approver_reject"` + DropCount *ebpf.MapSpec `ebpf:"drop_count"` + Enabled *ebpf.MapSpec `ebpf:"enabled"` + Events *ebpf.MapSpec `ebpf:"events"` + Scratch *ebpf.MapSpec `ebpf:"scratch"` + ScratchHeap *ebpf.MapSpec `ebpf:"scratch_heap"` +} + +// 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 { + ApproverFileEq *ebpf.Map `ebpf:"approver_file_eq"` + ApproverFileHeap *ebpf.Map `ebpf:"approver_file_heap"` + ApproverFilePre0 *ebpf.Map `ebpf:"approver_file_pre_0"` + ApproverFilePre1 *ebpf.Map `ebpf:"approver_file_pre_1"` + ApproverGen *ebpf.Map `ebpf:"approver_gen"` + ApproverLpmHeap *ebpf.Map `ebpf:"approver_lpm_heap"` + ApproverMode *ebpf.Map `ebpf:"approver_mode"` + ApproverPid *ebpf.Map `ebpf:"approver_pid"` + ApproverPort *ebpf.Map `ebpf:"approver_port"` + ApproverReject *ebpf.Map `ebpf:"approver_reject"` + DropCount *ebpf.Map `ebpf:"drop_count"` + Enabled *ebpf.Map `ebpf:"enabled"` + Events *ebpf.Map `ebpf:"events"` + Scratch *ebpf.Map `ebpf:"scratch"` + ScratchHeap *ebpf.Map `ebpf:"scratch_heap"` +} + +func (m *ProciterMaps) Close() error { + return _ProciterClose( + m.ApproverFileEq, + m.ApproverFileHeap, + m.ApproverFilePre0, + m.ApproverFilePre1, + m.ApproverGen, + m.ApproverLpmHeap, + m.ApproverMode, + m.ApproverPid, + m.ApproverPort, + m.ApproverReject, + m.DropCount, + m.Enabled, + m.Events, + m.Scratch, + m.ScratchHeap, + ) +} + +// 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/bpf/prociter_bpfel.o b/internal/ebpf/bpf/prociter_bpfel.o new file mode 100644 index 000000000..50f08fef8 Binary files /dev/null and b/internal/ebpf/bpf/prociter_bpfel.o differ diff --git a/internal/ebpf/btf.go b/internal/ebpf/btf.go new file mode 100644 index 000000000..0e4d96d78 --- /dev/null +++ b/internal/ebpf/btf.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 ebpf + +import ( + "fmt" + "runtime" +) + +func checkRuntimeSupport() (*PrerequisiteReport, error) { + if runtime.GOARCH != "amd64" { + return nil, fmt.Errorf("linux eBPF capture requires amd64, got %s", runtime.GOARCH) + } + return ProbePrerequisites() +} diff --git a/internal/ebpf/c/clone.bpf.c b/internal/ebpf/c/clone.bpf.c new file mode 100644 index 000000000..4e881d261 --- /dev/null +++ b/internal/ebpf/c/clone.bpf.c @@ -0,0 +1,160 @@ +//go:build ignore + +#include "common/events.h" +#include "bpf_tracing.h" + +char LICENSE[] SEC("license") = "Dual MIT/GPL"; + +static __always_inline int handle_clone_enter(u64 flags, u32 syscall_id) +{ + struct scratch_value *val; + + val = borrow_scratch(); + if (!val) + return 0; + val->flags = flags; + val->arg1 = syscall_id; + store_scratch(val); + return 0; +} + +static __always_inline int handle_clone_exit(long ret, u32 syscall_id) +{ + u64 key = bpf_get_current_pid_tgid(); + struct scratch_value *val; + struct syscall_event *e; + + /* Successful clones are emitted from sched_process_fork with child identity. + * Leave scratch in place so the fork handler can recover clone flags. + */ + if (ret >= 0) + return 0; + + if (!type_enabled(EVT_TYPE_CLONE)) { + bpf_map_delete_elem(&scratch, &key); + return 0; + } + + e = reserve_event(); + if (!e) { + bpf_map_delete_elem(&scratch, &key); + return 0; + } + + e->type = EVT_TYPE_CLONE; + e->syscall_id = syscall_id; + e->retval = ret; + fill_current_task(e); + + val = bpf_map_lookup_elem(&scratch, &key); + if (val) { + copy_scratch(e, val); + if (!e->syscall_id) + e->syscall_id = (u32)val->arg1; + } + bpf_map_delete_elem(&scratch, &key); + + bpf_ringbuf_submit(e, 0); + return 0; +} + +SEC("tp/syscalls/sys_enter_clone") +int handle_sys_enter_clone(struct trace_event_raw_sys_enter *ctx) +{ + return handle_clone_enter(ctx->args[0], (u32)ctx->id); +} + +SEC("tp/syscalls/sys_exit_clone") +int handle_sys_exit_clone(struct trace_event_raw_sys_exit *ctx) +{ + return handle_clone_exit(ctx->ret, (u32)ctx->id); +} + +SEC("tp/syscalls/sys_enter_clone3") +int handle_sys_enter_clone3(struct trace_event_raw_sys_enter *ctx) +{ + u64 flags = 0; + + bpf_probe_read_user(&flags, sizeof(flags), (const void *)ctx->args[0]); + return handle_clone_enter(flags, (u32)ctx->id); +} + +SEC("tp/syscalls/sys_exit_clone3") +int handle_sys_exit_clone3(struct trace_event_raw_sys_exit *ctx) +{ + return handle_clone_exit(ctx->ret, (u32)ctx->id); +} + +SEC("tp/syscalls/sys_enter_fork") +int handle_sys_enter_fork(struct trace_event_raw_sys_enter *ctx) +{ + return handle_clone_enter(0, (u32)ctx->id); +} + +SEC("tp/syscalls/sys_exit_fork") +int handle_sys_exit_fork(struct trace_event_raw_sys_exit *ctx) +{ + return handle_clone_exit(ctx->ret, (u32)ctx->id); +} + +SEC("tp/syscalls/sys_enter_vfork") +int handle_sys_enter_vfork(struct trace_event_raw_sys_enter *ctx) +{ + return handle_clone_enter(0, (u32)ctx->id); +} + +SEC("tp/syscalls/sys_exit_vfork") +int handle_sys_exit_vfork(struct trace_event_raw_sys_exit *ctx) +{ + return handle_clone_exit(ctx->ret, (u32)ctx->id); +} + +SEC("tp_btf/sched_process_fork") +int BPF_PROG(handle_sched_process_fork, struct task_struct *parent, struct task_struct *child) +{ + struct syscall_event *e; + struct scratch_value *val; + const struct cred *cred; + struct task_struct *real_parent; + u64 key; + + if (!child || !parent) + return 0; + if (!type_enabled(EVT_TYPE_CLONE)) + return 0; + + e = reserve_event(); + if (!e) + return 0; + + e->type = EVT_TYPE_CLONE; + e->retval = child->tgid; + e->pid = child->tgid; + e->tid = child->pid; + e->tgid = child->tgid; + e->start_boottime = child->start_boottime; + __builtin_memcpy(&e->comm, child->comm, sizeof(e->comm)); + + real_parent = child->real_parent; + if (real_parent) + e->ppid = real_parent->tgid; + else + e->ppid = parent->tgid; + + cred = child->real_cred; + if (cred) { + e->uid = cred->euid.val; + e->gid = cred->egid.val; + } + + key = ((u64)parent->tgid << 32) | (u32)parent->pid; + val = bpf_map_lookup_elem(&scratch, &key); + if (val) { + copy_scratch(e, val); + e->syscall_id = (u32)val->arg1; + bpf_map_delete_elem(&scratch, &key); + } + + bpf_ringbuf_submit(e, 0); + return 0; +} diff --git a/internal/ebpf/c/common/approvers.h b/internal/ebpf/c/common/approvers.h new file mode 100644 index 000000000..c9496b3f8 --- /dev/null +++ b/internal/ebpf/c/common/approvers.h @@ -0,0 +1,249 @@ +/* Conservative in-kernel approvers. Default-allow unless userspace + * populated a proven superset of equality/list/prefix predicates. + */ + +#pragma once + +#ifndef BPF_F_NO_PREALLOC +#define BPF_F_NO_PREALLOC (1U << 0) +#endif + +#define APPR_REQ_PID (1u << 0) +#define APPR_REQ_FILE (1u << 1) +#define APPR_REQ_PORT (1u << 2) + +#define APPR_GENS 2 +#define APPR_MODE_MAX (EVT_TYPE_MAX * APPR_GENS) + +/* There is no in-kernel glob matcher. A backtracking matcher forks a verifier + * path at every byte comparison, and even two patterns over 64 steps exhausts + * the 1M instruction budget. Userspace instead rewrites the patterns it can + * prove equivalent to a prefix into the LPM trie below, and leaves the rest + * default-allow. + */ + +struct approver_pid_key { + u32 gen; + u32 type; + u64 pid; +}; + +struct approver_port_key { + u32 gen; + u32 type; + u16 port; + u16 pad; +}; + +struct approver_file_key { + u32 gen; + u32 type; + u8 path[EVT_FILENAME_LEN]; +}; + +struct approver_lpm_key { + u32 prefixlen; + u8 path[EVT_FILENAME_LEN]; +}; + + +struct { + __uint(type, BPF_MAP_TYPE_ARRAY); + __uint(max_entries, 1); + __type(key, u32); + __type(value, u32); +} approver_gen SEC(".maps"); + +struct { + __uint(type, BPF_MAP_TYPE_ARRAY); + __uint(max_entries, APPR_MODE_MAX); + __type(key, u32); + __type(value, u8); +} approver_mode SEC(".maps"); + +struct { + __uint(type, BPF_MAP_TYPE_HASH); + __uint(max_entries, 1024); + __type(key, struct approver_pid_key); + __type(value, u8); +} approver_pid SEC(".maps"); + +struct { + __uint(type, BPF_MAP_TYPE_HASH); + __uint(max_entries, 1024); + __type(key, struct approver_port_key); + __type(value, u8); +} approver_port SEC(".maps"); + +struct { + __uint(type, BPF_MAP_TYPE_HASH); + __uint(max_entries, 1024); + __type(key, struct approver_file_key); + __type(value, u8); +} approver_file_eq SEC(".maps"); + +struct { + __uint(type, BPF_MAP_TYPE_LPM_TRIE); + __uint(max_entries, 256); + __uint(map_flags, BPF_F_NO_PREALLOC); + __type(key, struct approver_lpm_key); + __type(value, u8); +} approver_file_pre_0 SEC(".maps"); + +struct { + __uint(type, BPF_MAP_TYPE_LPM_TRIE); + __uint(max_entries, 256); + __uint(map_flags, BPF_F_NO_PREALLOC); + __type(key, struct approver_lpm_key); + __type(value, u8); +} approver_file_pre_1 SEC(".maps"); + +struct { + __uint(type, BPF_MAP_TYPE_PERCPU_ARRAY); + __uint(max_entries, 1); + __type(key, u32); + __type(value, struct approver_file_key); +} approver_file_heap SEC(".maps"); + +struct { + __uint(type, BPF_MAP_TYPE_PERCPU_ARRAY); + __uint(max_entries, 1); + __type(key, u32); + __type(value, struct approver_lpm_key); +} approver_lpm_heap SEC(".maps"); + +struct { + __uint(type, BPF_MAP_TYPE_ARRAY); + __uint(max_entries, 1); + __type(key, u32); + __type(value, u64); +} approver_reject SEC(".maps"); + + +static __always_inline void account_approver_reject(void) +{ + u32 key = 0; + u64 *count; + + count = bpf_map_lookup_elem(&approver_reject, &key); + if (!count) + return; + __sync_fetch_and_add(count, 1); +} + +static __always_inline u32 approver_generation(void) +{ + u32 key = 0; + u32 *gen; + + gen = bpf_map_lookup_elem(&approver_gen, &key); + if (!gen) + return 0; + return *gen & 1; +} + +static __always_inline u16 sockaddr_dport(const u8 *aux) +{ + u16 family; + u16 port; + + if (!aux) + return 0; + family = (u16)aux[0] | ((u16)aux[1] << 8); + if (family != 2 && family != 10) + return 0; + port = ((u16)aux[2] << 8) | aux[3]; + return port; +} + +static __always_inline int stash_filename(const u8 *filename) +{ + struct approver_file_key *exact; + u32 zero = 0; + + exact = bpf_map_lookup_elem(&approver_file_heap, &zero); + if (!exact) + return 0; + __builtin_memset(exact, 0, sizeof(*exact)); + if (filename) + __builtin_memcpy(exact->path, filename, EVT_FILENAME_LEN); + return 1; +} + +static __always_inline int approver_file_match(u32 gen, u32 type) +{ + struct approver_file_key *exact; + struct approver_lpm_key *lpm; + u32 zero = 0; + + exact = bpf_map_lookup_elem(&approver_file_heap, &zero); + if (exact) { + exact->gen = gen; + exact->type = type; + if (bpf_map_lookup_elem(&approver_file_eq, exact)) + return 1; + lpm = bpf_map_lookup_elem(&approver_lpm_heap, &zero); + if (lpm) { + __builtin_memset(lpm, 0, sizeof(*lpm)); + lpm->prefixlen = EVT_FILENAME_LEN * 8; + __builtin_memcpy(lpm->path, exact->path, EVT_FILENAME_LEN); + if (gen) { + if (bpf_map_lookup_elem(&approver_file_pre_1, lpm)) + return 1; + } else if (bpf_map_lookup_elem(&approver_file_pre_0, lpm)) { + return 1; + } + } + } + return 0; +} + +static __always_inline int event_approved(u32 type, u16 port, u32 truncated) +{ + u32 gen; + u32 mode_key; + u8 *mode; + struct approver_pid_key pkey = {}; + struct approver_port_key rkey = {}; + + if (type == EVT_TYPE_SNAPSHOT || type == EVT_TYPE_EXECVE || + type == EVT_TYPE_EXIT || type == EVT_TYPE_CLONE) + return 1; + if (type >= EVT_TYPE_MAX) + return 1; + + gen = approver_generation(); + mode_key = gen * EVT_TYPE_MAX + type; + if (mode_key >= APPR_MODE_MAX) + return 1; + mode = bpf_map_lookup_elem(&approver_mode, &mode_key); + if (!mode || *mode == 0) + return 1; + + if (*mode & APPR_REQ_PID) { + pkey.gen = gen; + pkey.type = type; + /* The init-namespace tgid, which is also what fill_current_ids puts on + * the event, so a ps.pid predicate compares like with like. + */ + pkey.pid = bpf_get_current_pid_tgid() >> 32; + if (!bpf_map_lookup_elem(&approver_pid, &pkey)) + return 0; + } + + if (*mode & APPR_REQ_FILE) { + if (!(truncated & TRUNC_FILENAME) && + !approver_file_match(gen, type)) + return 0; + } + + if (*mode & APPR_REQ_PORT) { + rkey.gen = gen; + rkey.type = type; + rkey.port = port; + if (!bpf_map_lookup_elem(&approver_port, &rkey)) + return 0; + } + + return 1; +} diff --git a/internal/ebpf/c/common/events.h b/internal/ebpf/c/common/events.h new file mode 100644 index 000000000..e9df5bc41 --- /dev/null +++ b/internal/ebpf/c/common/events.h @@ -0,0 +1,361 @@ +/* Shared event and map definitions for the Linux eBPF backend. */ + +#pragma once + +#include "vmlinux.h" +#include "bpf_helpers.h" +#include "bpf_core_read.h" + +#ifndef BPF_ANY +#define BPF_ANY 0 +#endif + +#define EVT_FILENAME_LEN 256 +#define EVT_TYPE_MAX 32 + +/* Set when a userspace copy was longer than the destination and was cut off. */ +#define TRUNC_FILENAME (1u << 0) /* filename[]: exec path, open/unlink/rename source */ +#define TRUNC_AUX (1u << 1) /* aux[]: rename destination or sockaddr bytes */ + +/* UAPI openat2 argument; not a CO-RE kernel type. */ +struct open_how { + u64 flags; + u64 mode; + u64 resolve; +}; + +struct trace_event_raw_sys_enter { + unsigned short common_type; + unsigned char common_flags; + unsigned char common_preempt_count; + int common_pid; + long id; + unsigned long args[6]; +}; + +struct trace_event_raw_sys_exit { + unsigned short common_type; + unsigned char common_flags; + unsigned char common_preempt_count; + int common_pid; + long id; + long ret; +}; + +/* Stable semantic type IDs. Keep in sync with pkg/event.Type on Linux. + * Zero is reserved for iter/task baseline snapshot records, which feed + * the process state and are never dispatched as events. + */ +#define EVT_TYPE_SNAPSHOT 0 +#define EVT_TYPE_EXECVE 1 +#define EVT_TYPE_EXIT 2 +#define EVT_TYPE_CLONE 3 +#define EVT_TYPE_OPENAT 4 +#define EVT_TYPE_UNLINK 5 +#define EVT_TYPE_RENAME 6 +#define EVT_TYPE_CONNECT 7 +#define EVT_TYPE_ACCEPT 8 +#define EVT_TYPE_MMAP 9 +#define EVT_TYPE_PROCESS_VM_READ 10 +#define EVT_TYPE_PROCESS_VM_WRITE 11 +#define EVT_TYPE_KILL 12 +#define EVT_TYPE_PTRACE 13 +#define EVT_TYPE_PRCTL 14 + +struct syscall_event { + u32 type; + u32 pid; + u32 tid; + u32 tgid; + u32 ppid; + u32 uid; + u32 gid; + u32 syscall_id; + s64 retval; + /* Interpreted per event type: clone flags, open flags, mmap flags, accept flags. */ + u64 flags; + /* Generic argument slots, interpreted per event type. */ + u64 arg0; + u64 arg1; + u64 arg2; + u64 arg3; + u64 start_boottime; + u64 timestamp_ns; + u32 truncated; + u32 pad; /* keeps comm[] 8-byte aligned; no semantic value */ + u8 comm[TASK_COMM_LEN]; + u8 filename[EVT_FILENAME_LEN]; /* exec path, open/unlink/rename source */ + u8 aux[EVT_FILENAME_LEN]; /* rename destination or sockaddr bytes */ +}; + +struct scratch_value { + u64 arg0; + u64 arg1; + u64 arg2; + u64 arg3; + u64 flags; + u32 truncated; + u32 pad; + u8 filename[EVT_FILENAME_LEN]; + u8 aux[EVT_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"); + +/* Correlates sys_enter state with the matching sys_exit. The task can + * migrate CPUs between entry and exit, so this must be a global hash, not + * a per-CPU one. LRU eviction reclaims entries whose exit never fired + * (e.g. the task was killed mid-syscall). + */ +struct { + __uint(type, BPF_MAP_TYPE_LRU_HASH); + __uint(max_entries, 2048); + __type(key, u64); + __type(value, struct scratch_value); +} scratch SEC(".maps"); + +struct { + __uint(type, BPF_MAP_TYPE_PERCPU_ARRAY); + __uint(max_entries, 1); + __type(key, u32); + __type(value, struct scratch_value); +} scratch_heap SEC(".maps"); + +struct { + __uint(type, BPF_MAP_TYPE_ARRAY); + __uint(max_entries, EVT_TYPE_MAX); + __type(key, u32); + __type(value, u8); +} enabled SEC(".maps"); + +#include "approvers.h" + +static __always_inline void 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); +} + +static __always_inline int type_enabled(u32 type) +{ + u8 *on; + + if (type >= EVT_TYPE_MAX) + return 0; + on = bpf_map_lookup_elem(&enabled, &type); + return on && *on; +} + +static __always_inline struct syscall_event *reserve_event(void) +{ + struct syscall_event *e; + + e = bpf_ringbuf_reserve(&events, sizeof(*e), 0); + if (!e) { + account_drop(); + return NULL; + } + __builtin_memset(e, 0, sizeof(*e)); + e->timestamp_ns = bpf_ktime_get_ns(); + return e; +} + +static __always_inline void fill_current_ids(struct syscall_event *e) +{ + u64 id = bpf_get_current_pid_tgid(); + u64 uidgid = bpf_get_current_uid_gid(); + + e->tgid = id >> 32; + e->tid = (u32)id; + e->pid = e->tgid; + e->uid = (u32)uidgid; + e->gid = uidgid >> 32; + bpf_get_current_comm(&e->comm, sizeof(e->comm)); +} + +static __always_inline void fill_current_task(struct syscall_event *e) +{ + struct task_struct *task; + struct task_struct *parent; + const struct cred *cred; + + fill_current_ids(e); + 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, euid.val); + e->gid = BPF_CORE_READ(cred, egid.val); + } +} + +static __always_inline u32 read_user_str(void *dst, u32 size, const char *src) +{ + long n; + + if (!src) + return 0; + n = bpf_probe_read_user_str(dst, size, src); + if (n == size) + return 1; + return 0; +} + +static __always_inline void copy_scratch(struct syscall_event *e, struct scratch_value *val) +{ + if (!val) + return; + e->arg0 = val->arg0; + e->arg1 = val->arg1; + e->arg2 = val->arg2; + e->arg3 = val->arg3; + if (!e->flags) + e->flags = val->flags; + e->truncated = val->truncated; + __builtin_memcpy(&e->filename, val->filename, sizeof(e->filename)); + __builtin_memcpy(&e->aux, val->aux, sizeof(e->aux)); +} + +static __always_inline struct scratch_value *borrow_scratch(void) +{ + u32 zero = 0; + struct scratch_value *val; + + val = bpf_map_lookup_elem(&scratch_heap, &zero); + if (!val) + return NULL; + __builtin_memset(val, 0, sizeof(*val)); + return val; +} + +static __always_inline int store_scratch(struct scratch_value *val) +{ + u64 key = bpf_get_current_pid_tgid(); + + return bpf_map_update_elem(&scratch, &key, val, BPF_ANY); +} + +static __always_inline int submit_from_scratch(u32 type, long ret, u32 syscall_id) +{ + u64 key = bpf_get_current_pid_tgid(); + struct scratch_value *val; + struct syscall_event *e; + u16 port = 0; + u32 truncated = 0; + + if (!type_enabled(type)) { + bpf_map_delete_elem(&scratch, &key); + return 0; + } + + val = bpf_map_lookup_elem(&scratch, &key); + if (val) { + truncated = val->truncated; + if (type == EVT_TYPE_CONNECT) + port = sockaddr_dport(val->aux); + stash_filename(val->filename); + } else { + stash_filename(NULL); + } + if (!event_approved(type, port, truncated)) { + account_approver_reject(); + bpf_map_delete_elem(&scratch, &key); + return 0; + } + + e = reserve_event(); + if (!e) { + bpf_map_delete_elem(&scratch, &key); + return 0; + } + + e->type = type; + e->syscall_id = syscall_id; + e->retval = ret; + fill_current_task(e); + val = bpf_map_lookup_elem(&scratch, &key); + if (val) + copy_scratch(e, val); + bpf_map_delete_elem(&scratch, &key); + bpf_ringbuf_submit(e, 0); + return 0; +} + +/* x86-64 syscall ABI. arg3 is r10, not rcx. */ +static __always_inline u64 syscall_nr(struct pt_regs *regs) +{ + return BPF_CORE_READ(regs, orig_ax); +} + +static __always_inline u64 syscall_arg0(struct pt_regs *regs) +{ + return BPF_CORE_READ(regs, di); +} + +static __always_inline u64 syscall_arg1(struct pt_regs *regs) +{ + return BPF_CORE_READ(regs, si); +} + +static __always_inline u64 syscall_arg2(struct pt_regs *regs) +{ + return BPF_CORE_READ(regs, dx); +} + +static __always_inline u64 syscall_arg3(struct pt_regs *regs) +{ + return BPF_CORE_READ(regs, r10); +} + +static __always_inline u64 syscall_arg4(struct pt_regs *regs) +{ + return BPF_CORE_READ(regs, r8); +} + +static __always_inline int submit_args(u32 type, long ret, u32 syscall_id, + u64 arg0, u64 arg1, u64 arg2, u64 arg3, u64 flags) +{ + struct syscall_event *e; + + if (!type_enabled(type)) + return 0; + stash_filename(NULL); + if (!event_approved(type, 0, 0)) { + account_approver_reject(); + return 0; + } + + e = reserve_event(); + if (!e) + return 0; + + e->type = type; + e->syscall_id = syscall_id; + e->retval = ret; + e->arg0 = arg0; + e->arg1 = arg1; + e->arg2 = arg2; + e->arg3 = arg3; + e->flags = flags; + fill_current_task(e); + bpf_ringbuf_submit(e, 0); + return 0; +} diff --git a/internal/ebpf/c/ctl.bpf.c b/internal/ebpf/c/ctl.bpf.c new file mode 100644 index 000000000..02cbb3ffe --- /dev/null +++ b/internal/ebpf/c/ctl.bpf.c @@ -0,0 +1,48 @@ +//go:build ignore + +#include "common/events.h" +#include "bpf_tracing.h" + +char LICENSE[] SEC("license") = "Dual MIT/GPL"; + +/* x86-64 syscall numbers. Register-only syscalls are captured at + * tp_btf/sys_exit, which supplies pt_regs (args + retval) so there is + * no enter probe or scratch slot. The per-syscall sys_exit tracepoint + * only carries id and ret. + */ +#define NR_PTRACE 101 +#define NR_KILL 62 +#define NR_TKILL 200 +#define NR_TGKILL 234 +#define NR_PRCTL 157 + +SEC("tp_btf/sys_exit") +int BPF_PROG(handle_sys_exit, struct pt_regs *regs, long ret) +{ + u64 id; + + if (!regs) + return 0; + id = syscall_nr(regs); + switch (id) { + case NR_KILL: + case NR_TKILL: + return submit_args(EVT_TYPE_KILL, ret, (u32)id, + syscall_arg0(regs), syscall_arg1(regs), 0, 0, 0); + case NR_TGKILL: + /* pid, tid, sig: emit the thread-group id and the signal. */ + return submit_args(EVT_TYPE_KILL, ret, (u32)id, + syscall_arg0(regs), syscall_arg2(regs), 0, 0, 0); + case NR_PTRACE: + return submit_args(EVT_TYPE_PTRACE, ret, (u32)id, + syscall_arg0(regs), syscall_arg1(regs), + syscall_arg2(regs), syscall_arg3(regs), 0); + case NR_PRCTL: + return submit_args(EVT_TYPE_PRCTL, ret, (u32)id, + syscall_arg0(regs), syscall_arg1(regs), + syscall_arg2(regs), syscall_arg3(regs), + syscall_arg4(regs)); + default: + return 0; + } +} diff --git a/internal/ebpf/c/execve.bpf.c b/internal/ebpf/c/execve.bpf.c new file mode 100644 index 000000000..afffb5740 --- /dev/null +++ b/internal/ebpf/c/execve.bpf.c @@ -0,0 +1,77 @@ +//go:build ignore + +#include "common/events.h" +#include "bpf_tracing.h" + +char LICENSE[] SEC("license") = "Dual MIT/GPL"; + +static __always_inline int handle_exec_enter(const char *filename, u32 syscall_id) +{ + struct scratch_value *val; + + val = borrow_scratch(); + if (!val) + return 0; + val->arg1 = syscall_id; + val->truncated |= read_user_str(val->filename, sizeof(val->filename), filename); + store_scratch(val); + return 0; +} + +static __always_inline int handle_exec_exit(long ret, u32 syscall_id) +{ + u64 key = bpf_get_current_pid_tgid(); + struct scratch_value *val; + struct syscall_event *e; + + if (!type_enabled(EVT_TYPE_EXECVE)) { + bpf_map_delete_elem(&scratch, &key); + return 0; + } + + e = reserve_event(); + if (!e) { + bpf_map_delete_elem(&scratch, &key); + return 0; + } + + e->type = EVT_TYPE_EXECVE; + e->syscall_id = syscall_id; + e->retval = ret; + fill_current_task(e); + + val = bpf_map_lookup_elem(&scratch, &key); + if (val) { + if (!e->syscall_id) + e->syscall_id = (u32)val->arg1; + copy_scratch(e, val); + } + bpf_map_delete_elem(&scratch, &key); + + bpf_ringbuf_submit(e, 0); + return 0; +} + +SEC("tp/syscalls/sys_enter_execve") +int handle_sys_enter_execve(struct trace_event_raw_sys_enter *ctx) +{ + return handle_exec_enter((const char *)ctx->args[0], (u32)ctx->id); +} + +SEC("tp/syscalls/sys_exit_execve") +int handle_sys_exit_execve(struct trace_event_raw_sys_exit *ctx) +{ + return handle_exec_exit(ctx->ret, (u32)ctx->id); +} + +SEC("tp/syscalls/sys_enter_execveat") +int handle_sys_enter_execveat(struct trace_event_raw_sys_enter *ctx) +{ + return handle_exec_enter((const char *)ctx->args[1], (u32)ctx->id); +} + +SEC("tp/syscalls/sys_exit_execveat") +int handle_sys_exit_execveat(struct trace_event_raw_sys_exit *ctx) +{ + return handle_exec_exit(ctx->ret, (u32)ctx->id); +} diff --git a/internal/ebpf/c/exit.bpf.c b/internal/ebpf/c/exit.bpf.c new file mode 100644 index 000000000..ead1dadfd --- /dev/null +++ b/internal/ebpf/c/exit.bpf.c @@ -0,0 +1,57 @@ +//go:build ignore + +#include "common/events.h" +#include "bpf_core_read.h" +#include "bpf_tracing.h" + +char LICENSE[] SEC("license") = "Dual MIT/GPL"; + +/* Process exits are captured from sched_process_exit rather than the + * syscalls/sys_exit_{exit,exit_group} tracepoints: those syscalls never + * return, so their exit tracepoints never fire. The scheduler hook also + * covers processes terminated by signals, which never enter exit_group. + */ +SEC("tp_btf/sched_process_exit") +int BPF_PROG(handle_sched_process_exit, struct task_struct *task) +{ + struct syscall_event *e; + struct task_struct *parent; + const struct cred *cred; + + if (!task) + return 0; + + /* Only emit process exits from the thread-group leader; thread + * exits are not process exits. + */ + if (task->pid != task->tgid) + return 0; + if (!type_enabled(EVT_TYPE_EXIT)) + return 0; + + e = reserve_event(); + if (!e) + return 0; + + e->type = EVT_TYPE_EXIT; + /* Raw wait status: (code << 8) | termination signal. */ + e->retval = task->exit_code; + e->pid = task->tgid; + e->tid = task->pid; + e->tgid = task->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->euid.val; + e->gid = cred->egid.val; + } + + bpf_ringbuf_submit(e, 0); + return 0; +} diff --git a/internal/ebpf/c/file.bpf.c b/internal/ebpf/c/file.bpf.c new file mode 100644 index 000000000..5e5353780 --- /dev/null +++ b/internal/ebpf/c/file.bpf.c @@ -0,0 +1,158 @@ +//go:build ignore + +#include "common/events.h" +#include "bpf_tracing.h" + +char LICENSE[] SEC("license") = "Dual MIT/GPL"; + +static __always_inline int handle_openat_enter(s64 dirfd, const char *pathname, u64 flags, u64 mode) +{ + struct scratch_value *val; + + if (!type_enabled(EVT_TYPE_OPENAT)) + return 0; + val = borrow_scratch(); + if (!val) + return 0; + val->arg0 = (u64)dirfd; + val->arg1 = mode; + val->flags = flags; + val->truncated |= read_user_str(val->filename, sizeof(val->filename), pathname); + store_scratch(val); + return 0; +} + +SEC("tp/syscalls/sys_enter_open") +int handle_sys_enter_open(struct trace_event_raw_sys_enter *ctx) +{ + return handle_openat_enter(-100 /* AT_FDCWD */, (const char *)ctx->args[0], ctx->args[1], ctx->args[2]); +} + +SEC("tp/syscalls/sys_exit_open") +int handle_sys_exit_open(struct trace_event_raw_sys_exit *ctx) +{ + return submit_from_scratch(EVT_TYPE_OPENAT, ctx->ret, (u32)ctx->id); +} + +SEC("tp/syscalls/sys_enter_openat") +int handle_sys_enter_openat(struct trace_event_raw_sys_enter *ctx) +{ + return handle_openat_enter((s64)ctx->args[0], (const char *)ctx->args[1], ctx->args[2], ctx->args[3]); +} + +SEC("tp/syscalls/sys_exit_openat") +int handle_sys_exit_openat(struct trace_event_raw_sys_exit *ctx) +{ + return submit_from_scratch(EVT_TYPE_OPENAT, ctx->ret, (u32)ctx->id); +} + +SEC("tp/syscalls/sys_enter_openat2") +int handle_sys_enter_openat2(struct trace_event_raw_sys_enter *ctx) +{ + struct open_how how = {}; + + if (ctx->args[2]) + bpf_probe_read_user(&how, sizeof(how), (const void *)ctx->args[2]); + return handle_openat_enter((s64)ctx->args[0], (const char *)ctx->args[1], how.flags, how.mode); +} + +SEC("tp/syscalls/sys_exit_openat2") +int handle_sys_exit_openat2(struct trace_event_raw_sys_exit *ctx) +{ + return submit_from_scratch(EVT_TYPE_OPENAT, ctx->ret, (u32)ctx->id); +} + +static __always_inline int handle_unlink_enter(s64 dirfd, const char *pathname, u64 flags) +{ + struct scratch_value *val; + + if (!type_enabled(EVT_TYPE_UNLINK)) + return 0; + val = borrow_scratch(); + if (!val) + return 0; + val->arg0 = (u64)dirfd; + val->flags = flags; + val->truncated |= read_user_str(val->filename, sizeof(val->filename), pathname); + store_scratch(val); + return 0; +} + +SEC("tp/syscalls/sys_enter_unlink") +int handle_sys_enter_unlink(struct trace_event_raw_sys_enter *ctx) +{ + return handle_unlink_enter(-100 /* AT_FDCWD */, (const char *)ctx->args[0], 0); +} + +SEC("tp/syscalls/sys_exit_unlink") +int handle_sys_exit_unlink(struct trace_event_raw_sys_exit *ctx) +{ + return submit_from_scratch(EVT_TYPE_UNLINK, ctx->ret, (u32)ctx->id); +} + +SEC("tp/syscalls/sys_enter_unlinkat") +int handle_sys_enter_unlinkat(struct trace_event_raw_sys_enter *ctx) +{ + return handle_unlink_enter((s64)ctx->args[0], (const char *)ctx->args[1], ctx->args[2]); +} + +SEC("tp/syscalls/sys_exit_unlinkat") +int handle_sys_exit_unlinkat(struct trace_event_raw_sys_exit *ctx) +{ + return submit_from_scratch(EVT_TYPE_UNLINK, ctx->ret, (u32)ctx->id); +} + +static __always_inline int handle_rename_enter(s64 olddirfd, const char *oldpath, s64 newdirfd, const char *newpath, u64 flags) +{ + struct scratch_value *val; + + if (!type_enabled(EVT_TYPE_RENAME)) + return 0; + val = borrow_scratch(); + if (!val) + return 0; + val->arg0 = (u64)olddirfd; + val->arg1 = (u64)newdirfd; + val->flags = flags; + val->truncated |= read_user_str(val->filename, sizeof(val->filename), oldpath); + if (read_user_str(val->aux, sizeof(val->aux), newpath)) + val->truncated |= TRUNC_AUX; + store_scratch(val); + return 0; +} + +SEC("tp/syscalls/sys_enter_rename") +int handle_sys_enter_rename(struct trace_event_raw_sys_enter *ctx) +{ + return handle_rename_enter(-100 /* AT_FDCWD */, (const char *)ctx->args[0], -100, (const char *)ctx->args[1], 0); +} + +SEC("tp/syscalls/sys_exit_rename") +int handle_sys_exit_rename(struct trace_event_raw_sys_exit *ctx) +{ + return submit_from_scratch(EVT_TYPE_RENAME, ctx->ret, (u32)ctx->id); +} + +SEC("tp/syscalls/sys_enter_renameat") +int handle_sys_enter_renameat(struct trace_event_raw_sys_enter *ctx) +{ + return handle_rename_enter((s64)ctx->args[0], (const char *)ctx->args[1], (s64)ctx->args[2], (const char *)ctx->args[3], 0); +} + +SEC("tp/syscalls/sys_exit_renameat") +int handle_sys_exit_renameat(struct trace_event_raw_sys_exit *ctx) +{ + return submit_from_scratch(EVT_TYPE_RENAME, ctx->ret, (u32)ctx->id); +} + +SEC("tp/syscalls/sys_enter_renameat2") +int handle_sys_enter_renameat2(struct trace_event_raw_sys_enter *ctx) +{ + return handle_rename_enter((s64)ctx->args[0], (const char *)ctx->args[1], (s64)ctx->args[2], (const char *)ctx->args[3], ctx->args[4]); +} + +SEC("tp/syscalls/sys_exit_renameat2") +int handle_sys_exit_renameat2(struct trace_event_raw_sys_exit *ctx) +{ + return submit_from_scratch(EVT_TYPE_RENAME, ctx->ret, (u32)ctx->id); +} diff --git a/internal/ebpf/c/mem.bpf.c b/internal/ebpf/c/mem.bpf.c new file mode 100644 index 000000000..de77d9c6e --- /dev/null +++ b/internal/ebpf/c/mem.bpf.c @@ -0,0 +1,81 @@ +//go:build ignore + +#include "common/events.h" +#include "bpf_tracing.h" + +char LICENSE[] SEC("license") = "Dual MIT/GPL"; + +struct iovec { + u64 iov_base; + u64 iov_len; +}; + +SEC("tp/syscalls/sys_enter_mmap") +int handle_sys_enter_mmap(struct trace_event_raw_sys_enter *ctx) +{ + struct scratch_value *val; + + if (!type_enabled(EVT_TYPE_MMAP)) + return 0; + val = borrow_scratch(); + if (!val) + return 0; + val->arg0 = ctx->args[5]; /* offset */ + val->arg1 = ctx->args[1]; /* length */ + val->arg2 = ctx->args[2]; /* prot */ + val->arg3 = ctx->args[4]; /* fd */ + val->flags = ctx->args[3]; + store_scratch(val); + return 0; +} + +SEC("tp/syscalls/sys_exit_mmap") +int handle_sys_exit_mmap(struct trace_event_raw_sys_exit *ctx) +{ + return submit_from_scratch(EVT_TYPE_MMAP, ctx->ret, (u32)ctx->id); +} + +static __always_inline int handle_process_vm_enter(u32 type, u64 pid, const void *rvec, u64 flags) +{ + struct scratch_value *val; + struct iovec iov = {}; + + if (!type_enabled(type)) + return 0; + val = borrow_scratch(); + if (!val) + return 0; + val->arg0 = pid; + val->flags = flags; + if (rvec) { + bpf_probe_read_user(&iov, sizeof(iov), rvec); + val->arg2 = iov.iov_base; + val->arg3 = iov.iov_len; + } + store_scratch(val); + return 0; +} + +SEC("tp/syscalls/sys_enter_process_vm_readv") +int handle_sys_enter_process_vm_readv(struct trace_event_raw_sys_enter *ctx) +{ + return handle_process_vm_enter(EVT_TYPE_PROCESS_VM_READ, ctx->args[0], (const void *)ctx->args[3], ctx->args[5]); +} + +SEC("tp/syscalls/sys_exit_process_vm_readv") +int handle_sys_exit_process_vm_readv(struct trace_event_raw_sys_exit *ctx) +{ + return submit_from_scratch(EVT_TYPE_PROCESS_VM_READ, ctx->ret, (u32)ctx->id); +} + +SEC("tp/syscalls/sys_enter_process_vm_writev") +int handle_sys_enter_process_vm_writev(struct trace_event_raw_sys_enter *ctx) +{ + return handle_process_vm_enter(EVT_TYPE_PROCESS_VM_WRITE, ctx->args[0], (const void *)ctx->args[3], ctx->args[5]); +} + +SEC("tp/syscalls/sys_exit_process_vm_writev") +int handle_sys_exit_process_vm_writev(struct trace_event_raw_sys_exit *ctx) +{ + return submit_from_scratch(EVT_TYPE_PROCESS_VM_WRITE, ctx->ret, (u32)ctx->id); +} diff --git a/internal/ebpf/c/net.bpf.c b/internal/ebpf/c/net.bpf.c new file mode 100644 index 000000000..9df0001eb --- /dev/null +++ b/internal/ebpf/c/net.bpf.c @@ -0,0 +1,103 @@ +//go:build ignore + +#include "common/events.h" +#include "bpf_tracing.h" + +char LICENSE[] SEC("license") = "Dual MIT/GPL"; + +/* Copy exactly addrlen bytes: a fixed-size read past the caller's sockaddr + * can cross into an unmapped page and fail wholesale, losing the address. + */ +static __always_inline void read_sockaddr(struct scratch_value *val, const void *addr, u64 addrlen) +{ + u64 len = addrlen; + + if (len > sizeof(val->aux)) { + len = sizeof(val->aux); + val->truncated |= TRUNC_AUX; + } + if (addr && len) + bpf_probe_read_user(val->aux, len, addr); +} + +SEC("tp/syscalls/sys_enter_connect") +int handle_sys_enter_connect(struct trace_event_raw_sys_enter *ctx) +{ + struct scratch_value *val; + + if (!type_enabled(EVT_TYPE_CONNECT)) + return 0; + val = borrow_scratch(); + if (!val) + return 0; + val->arg0 = ctx->args[0]; + val->arg1 = ctx->args[2]; + read_sockaddr(val, (const void *)ctx->args[1], ctx->args[2]); + store_scratch(val); + return 0; +} + +SEC("tp/syscalls/sys_exit_connect") +int handle_sys_exit_connect(struct trace_event_raw_sys_exit *ctx) +{ + return submit_from_scratch(EVT_TYPE_CONNECT, ctx->ret, (u32)ctx->id); +} + +static __always_inline int handle_accept_enter(u64 fd, const void *addr, const void *addrlen, u64 flags) +{ + struct scratch_value *val; + + if (!type_enabled(EVT_TYPE_ACCEPT)) + return 0; + val = borrow_scratch(); + if (!val) + return 0; + val->arg0 = fd; + val->arg1 = (u64)addrlen; + val->arg2 = (u64)addr; + val->flags = flags; + store_scratch(val); + return 0; +} + +/* addrlen is value-result: the kernel writes the peer address and its actual + * size only once accept returns, so the sockaddr is copied at exit. + */ +static __always_inline int handle_accept_exit(long ret, u32 syscall_id) +{ + u64 key = bpf_get_current_pid_tgid(); + struct scratch_value *val; + u32 addrlen = 0; + + val = bpf_map_lookup_elem(&scratch, &key); + if (val && val->arg2 && ret >= 0) { + if (val->arg1) + bpf_probe_read_user(&addrlen, sizeof(addrlen), (const void *)val->arg1); + read_sockaddr(val, (const void *)val->arg2, addrlen); + } + return submit_from_scratch(EVT_TYPE_ACCEPT, ret, syscall_id); +} + +SEC("tp/syscalls/sys_enter_accept") +int handle_sys_enter_accept(struct trace_event_raw_sys_enter *ctx) +{ + return handle_accept_enter(ctx->args[0], (const void *)ctx->args[1], (const void *)ctx->args[2], 0); +} + +SEC("tp/syscalls/sys_exit_accept") +int handle_sys_exit_accept(struct trace_event_raw_sys_exit *ctx) +{ + return handle_accept_exit(ctx->ret, (u32)ctx->id); +} + +SEC("tp/syscalls/sys_enter_accept4") +int handle_sys_enter_accept4(struct trace_event_raw_sys_enter *ctx) +{ + return handle_accept_enter(ctx->args[0], (const void *)ctx->args[1], (const void *)ctx->args[2], ctx->args[3]); +} + +SEC("tp/syscalls/sys_exit_accept4") +int handle_sys_exit_accept4(struct trace_event_raw_sys_exit *ctx) +{ + return handle_accept_exit(ctx->ret, (u32)ctx->id); +} diff --git a/internal/ebpf/c/prociter.bpf.c b/internal/ebpf/c/prociter.bpf.c new file mode 100644 index 000000000..628a190cf --- /dev/null +++ b/internal/ebpf/c/prociter.bpf.c @@ -0,0 +1,59 @@ +//go:build ignore + +#include "common/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 syscall_event *e; + pid_t pid; + pid_t tgid; + + task = ctx->task; + if (!task) + return 0; + + pid = task->pid; + tgid = task->tgid; + if (pid != tgid) + return 0; + + e = reserve_event(); + if (!e) + return 0; + + e->type = EVT_TYPE_SNAPSHOT; + e->pid = tgid; + e->tid = 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->euid.val; + e->gid = cred->egid.val; + } + + bpf_ringbuf_submit(e, 0); + return 0; +} diff --git a/internal/ebpf/consumer.go b/internal/ebpf/consumer.go new file mode 100644 index 000000000..a0c893aa8 --- /dev/null +++ b/internal/ebpf/consumer.go @@ -0,0 +1,228 @@ +//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 ebpf + +import ( + "expvar" + + "github.com/rabbitstack/fibratus/pkg/event" + "github.com/rabbitstack/fibratus/pkg/event/params" + "github.com/rabbitstack/fibratus/pkg/ps" + pstypes "github.com/rabbitstack/fibratus/pkg/ps/types" + "github.com/rabbitstack/fibratus/pkg/util/va" +) + +var ( + eventsProcessed = expvar.NewInt("ebpf.events.processed") + eventsExcluded = expvar.NewInt("ebpf.events.excluded") + eventsUnknown = expvar.NewInt("ebpf.events.unknown") + parseErrors = expvar.NewInt("ebpf.events.parse.errors") + pendingQueued = expvar.NewInt("ebpf.startup.pending.queued") + pendingDropped = expvar.NewInt("ebpf.startup.pending.dropped") + replayApplied = expvar.NewInt("ebpf.startup.replay.applied") + snapshotUpserts = expvar.NewInt("ebpf.startup.snapshot.upserts") + lateSnapshots = expvar.NewInt("ebpf.startup.snapshot.late") + enrichmentMiss = expvar.NewInt("ebpf.enrichment.miss") + ringbufDrops = expvar.NewInt("ebpf.ringbuf.drops") + approverDrops = expvar.NewInt("ebpf.approver.drops") +) + +func applyProcessState(psnap ps.Snapshotter, evt *event.Event) { + if evt == nil || psnap == nil { + return + } + switch { + case evt.Type == event.Execve && succeeded(evt): + ps := buildPS(evt, psnap) + evt.PS = ps + _ = psnap.Write(evt) + case evt.Type == event.Clone && succeeded(evt) && evt.IsCreateProcess(): + ps := buildPS(evt, psnap) + evt.PS = ps + psnap.Put(ps) + case evt.Type == event.Clone && succeeded(evt) && evt.IsCreateThread(): + ok, existing := psnap.Find(evt.PID) + if ok && existing != nil { + evt.PS = existing + _ = psnap.AddThread(evt) + } + case evt.Type == event.Mmap && succeeded(evt): + ok, existing := psnap.Find(evt.PID) + if ok && existing != nil { + evt.PS = existing + if retainMmap(evt) { + existing.AddMmap(pstypes.Mmap{ + BaseAddress: va.Address(evt.GetParamAsUint64(params.MemBaseAddress)), + Size: evt.GetParamAsUint64(params.MemRegionSize), + Protection: evt.GetParamAsUint32(params.MemProtect), + Type: mmapKind(evt.GetParamAsUint64(params.MmapFlags)), + }) + } + } + case evt.Type == event.Exit: + ok, existing := psnap.Find(evt.PID) + if ok { + evt.PS = existing + } + _ = psnap.Remove(evt) + default: + ok, existing := psnap.Find(evt.PID) + if ok { + evt.PS = existing + } + } + if evt.PS == nil { + ok, existing := psnap.Find(evt.PID) + if ok { + evt.PS = existing + } + } +} + +func upsertSnapshot(psnap ps.Snapshotter, rec *pstypes.PS) { + if psnap == nil || rec == nil { + return + } + ok, existing := psnap.Find(rec.PID) + if !ok || existing == nil { + psnap.Put(rec) + snapshotUpserts.Add(1) + return + } + if existing.StartBootTime != rec.StartBootTime { + psnap.Put(rec) + snapshotUpserts.Add(1) + return + } + mergePS(existing, rec) + snapshotUpserts.Add(1) +} + +func mergePS(dst, src *pstypes.PS) { + if src.Name != "" { + dst.Name = src.Name + } + if src.Exe != "" { + dst.Exe = src.Exe + } + if src.Cmdline != "" { + dst.Cmdline = src.Cmdline + } + if src.Ppid != 0 { + dst.Ppid = src.Ppid + } + if src.UID != 0 { + dst.UID = src.UID + } + if src.GID != 0 { + dst.GID = src.GID + } + if src.StartBootTime != 0 { + dst.StartBootTime = src.StartBootTime + } +} + +func buildPS(evt *event.Event, psnap ps.Snapshotter) *pstypes.PS { + ok, existing := psnap.Find(evt.PID) + exe := evt.GetParamAsString(params.Exe) + cmdline := evt.GetParamAsString(params.Cmdline) + name := evt.GetParamAsString(params.ProcessName) + if exe == "" && existing != nil { + exe = existing.Exe + } + if cmdline == "" && existing != nil { + cmdline = existing.Cmdline + } + if name == "" { + name = baseName(exe) + } + ps := &pstypes.PS{ + PID: evt.PID, + Ppid: evt.GetParamAsUint32(params.ProcessParentID), + Name: name, + Cmdline: cmdline, + Exe: exe, + Args: splitCmdline(cmdline), + StartBootTime: evt.GetParamAsUint64(params.StartBootTime), + UID: evt.GetParamAsUint32(params.UID), + GID: evt.GetParamAsUint32(params.GID), + Threads: make(map[uint32]pstypes.Thread), + } + if ok && existing != nil && existing.StartBootTime == ps.StartBootTime && existing.Threads != nil { + ps.Threads = existing.Threads + ps.Parent = existing.Parent + } + if ok, parent := psnap.Find(ps.Ppid); ok { + ps.Parent = parent + } + return ps +} + +func succeeded(evt *event.Event) bool { + ret, err := evt.Params.GetInt64(params.Retval) + if err != nil { + return true + } + return ret >= 0 +} + +const mapAnonymous = 0x20 + +func mmapKind(flags uint64) string { + if flags&mapAnonymous != 0 { + return "anonymous" + } + return "file" +} + +// retainMmap reports whether the mapping should be stored on process state. +// Anonymous mappings are frequent (heap, stacks, JIT) and we do not yet +// hook munmap, so keeping them would grow without bound. File-backed +// mappings are the useful set (shared objects, mapped files). +func retainMmap(evt *event.Event) bool { + if mmapKind(evt.GetParamAsUint64(params.MmapFlags)) != "file" { + return false + } + fd, err := evt.Params.GetInt64(params.FD) + if err != nil { + return false + } + return fd >= 0 +} + +func enrichEvent(evt *event.Event) { + if evt == nil { + return + } + exe, cmdline, err := enrichFromProc(evt.PID) + if err != nil { + enrichmentMiss.Add(1) + } + if exe != "" { + evt.Params.Append(params.Exe, params.Path, exe) + if evt.GetParamAsString(params.ProcessName) == "" { + evt.Params.Append(params.ProcessName, params.String, baseName(exe)) + } + } + if cmdline != "" { + evt.Params.Append(params.Cmdline, params.String, cmdline) + } +} diff --git a/internal/ebpf/consumer_test.go b/internal/ebpf/consumer_test.go new file mode 100644 index 000000000..edc6d1646 --- /dev/null +++ b/internal/ebpf/consumer_test.go @@ -0,0 +1,98 @@ +//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 ebpf + +import ( + "testing" + + "github.com/rabbitstack/fibratus/pkg/event" + "github.com/rabbitstack/fibratus/pkg/event/params" + "github.com/rabbitstack/fibratus/pkg/ps" + pstypes "github.com/rabbitstack/fibratus/pkg/ps/types" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestApplyProcessStateExecveAndPIDReuse(t *testing.T) { + snap := ps.NewSnapshotter() + first := sampleExecve().toEvent() + applyProcessState(snap, first) + ok, got := snap.Find(4242) + require.True(t, ok) + assert.Equal(t, "/bin/bash", got.Exe) + assert.Equal(t, uint64(123456789), got.StartBootTime) + assert.Equal(t, got.UUID(), first.PS.UUID()) + + reuse := sampleExecve().toEvent() + reuse.Params.Append(params.StartBootTime, params.Uint64, uint64(999)) + reuse.Params.Append(params.Exe, params.Path, "/bin/sh") + reuse.Params.Append(params.ProcessName, params.String, "sh") + applyProcessState(snap, reuse) + ok, got = snap.Find(4242) + require.True(t, ok) + assert.Equal(t, "/bin/sh", got.Exe) + assert.Equal(t, uint64(999), got.StartBootTime) + assert.NotEqual(t, first.PS.UUID(), got.UUID()) +} + +func TestApplyProcessStateExitRemoves(t *testing.T) { + snap := ps.NewSnapshotter() + evt := sampleExecve().toEvent() + applyProcessState(snap, evt) + exit := &event.Event{ + Type: event.Exit, + PID: 4242, + Params: event.Params{}, + } + exit.Params.Append(params.Retval, params.Int64, int64(0)) + applyProcessState(snap, exit) + ok, _ := snap.Find(4242) + assert.False(t, ok) +} + +func TestUpsertSnapshotIgnoresAfterLiveReplacement(t *testing.T) { + snap := ps.NewSnapshotter() + rec := &pstypes.PS{PID: 7, Name: "snap", StartBootTime: 9, Exe: "/bin/snap"} + upsertSnapshot(snap, rec) + ok, got := snap.Find(7) + require.True(t, ok) + assert.Equal(t, "snap", got.Name) + + live := &event.Event{Type: event.Execve, PID: 7, Params: event.Params{}} + live.Params.Append(params.ProcessName, params.String, "live") + live.Params.Append(params.Exe, params.Path, "/bin/live") + live.Params.Append(params.StartBootTime, params.Uint64, uint64(9)) + live.Params.Append(params.Retval, params.Int64, int64(0)) + applyProcessState(snap, live) + + upsertSnapshot(snap, &pstypes.PS{PID: 7, Name: "stale", StartBootTime: 9, Exe: "/bin/stale"}) + ok, got = snap.Find(7) + require.True(t, ok) + assert.Equal(t, "stale", got.Name) +} + +func TestPendingBackpressure(t *testing.T) { + es := &EventSource{pendingCap: 2} + require.True(t, es.enqueuePending(&event.Event{PID: 1})) + require.True(t, es.enqueuePending(&event.Event{PID: 2})) + require.False(t, es.enqueuePending(&event.Event{PID: 3})) + assert.Len(t, es.pending, 2) +} diff --git a/internal/ebpf/doc.go b/internal/ebpf/doc.go new file mode 100644 index 000000000..97119d250 --- /dev/null +++ b/internal/ebpf/doc.go @@ -0,0 +1,26 @@ +/* + * 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 ebpf hosts the Linux eBPF instrumentation backend. The event +// source loads CO-RE programs, captures process, file, network, memory, +// and process-control syscalls, and reconciles live events against an +// iter/task baseline. Optional in-kernel approvers drop events that cannot +// match compiled rules or the CLI filter, using only positive equality, +// list, and prefix predicates. The spike subdirectory remains as a +// feasibility prototype. +package ebpf diff --git a/internal/ebpf/enrich.go b/internal/ebpf/enrich.go new file mode 100644 index 000000000..dcd8f6049 --- /dev/null +++ b/internal/ebpf/enrich.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 ebpf + +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) { + exe, err = os.Readlink(fmt.Sprintf("/proc/%d/exe", pid)) + 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") + cleaned := make([]string, 0, len(parts)) + for _, p := range parts { + if p != "" { + cleaned = append(cleaned, p) + } + } + return exe, strings.Join(cleaned, " "), err +} diff --git a/internal/ebpf/events.go b/internal/ebpf/events.go new file mode 100644 index 000000000..6ec7aa2fb --- /dev/null +++ b/internal/ebpf/events.go @@ -0,0 +1,185 @@ +//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 ebpf + +import ( + "bytes" + "encoding/binary" + "fmt" + "time" + + "github.com/rabbitstack/fibratus/pkg/event" + "github.com/rabbitstack/fibratus/pkg/event/params" + "github.com/rabbitstack/fibratus/pkg/util/hostname" +) + +const ( + // snapshotType marks iter/task baseline records. It maps to + // event.UnknownType, so snapshots can never leak as live events. + snapshotType = 0 + + commLen = 16 + filenameLen = 256 +) + +// rawEvent mirrors struct syscall_event in c/common/events.h. +type rawEvent struct { + Type uint32 + PID uint32 + TID uint32 + TGID uint32 + PPID uint32 + UID uint32 + GID uint32 + SyscallID uint32 + Retval int64 + Flags uint64 + Arg0 uint64 + Arg1 uint64 + Arg2 uint64 + Arg3 uint64 + StartBootTime uint64 + TimestampNs uint64 + Truncated uint32 + Pad uint32 + Comm [commLen]byte + Filename [filenameLen]byte + Aux [filenameLen]byte +} + +func decodeRawEvent(raw []byte) (rawEvent, error) { + var ev rawEvent + if err := binary.Read(bytes.NewReader(raw), binary.LittleEndian, &ev); err != nil { + return ev, fmt.Errorf("decoding eBPF event: %w", err) + } + return ev, nil +} + +func (r rawEvent) comm() string { return cString(r.Comm[:]) } +func (r rawEvent) filename() string { return cString(r.Filename[:]) } +func (r rawEvent) aux() string { return cString(r.Aux[:]) } + +func (r rawEvent) eventType() event.Type { + return event.Type(r.Type) +} + +func (r rawEvent) processID() uint32 { + if r.PID != 0 { + return r.PID + } + return r.TGID +} + +// toEvent converts the raw eBPF record into an event. The sequence number is +// assigned at dispatch time, mirroring the Windows consumer which increments +// the sequencer only for events that pass exclusion and filtering. +func (r rawEvent) toEvent() *event.Event { + typ := r.eventType() + evt := &event.Event{ + PID: r.processID(), + Tid: r.TID, + Type: typ, + Host: hostname.Get(), + Timestamp: time.Unix(0, int64(r.TimestampNs)), + Params: event.Params{}, + Metadata: make(event.Metadata), + } + evt.Params.Append(params.ProcessID, params.PID, evt.PID) + evt.Params.Append(params.ThreadID, params.TID, evt.Tid) + evt.Params.Append(params.ProcessParentID, params.PID, r.PPID) + evt.Params.Append(params.ProcessName, params.String, r.comm()) + evt.Params.Append(params.UID, params.Uint32, r.UID) + evt.Params.Append(params.GID, params.Uint32, r.GID) + evt.Params.Append(params.SyscallID, params.Uint32, r.SyscallID) + evt.Params.Append(params.Retval, params.Int64, r.Retval) + evt.Params.Append(params.StartBootTime, params.Uint64, r.StartBootTime) + + switch typ { + case event.Execve: + name := r.filename() + if name == "" { + name = r.comm() + } + evt.Params.Append(params.Exe, params.Path, name) + evt.Params.Append(params.Cmdline, params.String, name) + case event.Exit: + evt.Params.Append(params.ExitStatus, params.Int64, r.Retval) + case event.Clone: + evt.Params.Append(params.CloneFlags, params.Uint64, r.Flags) + case event.Openat: + evt.Params.Append(params.DirFD, params.Int64, int64(r.Arg0)) + evt.Params.Append(params.FilePath, params.Path, r.filename()) + evt.Params.Append(params.FileFlags, params.Uint64, r.Flags) + evt.Params.Append(params.FileMode, params.Uint64, r.Arg1) + if r.Retval >= 0 { + evt.Params.Append(params.FD, params.Int64, r.Retval) + } + case event.Unlink: + evt.Params.Append(params.DirFD, params.Int64, int64(r.Arg0)) + evt.Params.Append(params.FilePath, params.Path, r.filename()) + evt.Params.Append(params.FileFlags, params.Uint64, r.Flags) + case event.Rename: + evt.Params.Append(params.DirFD, params.Int64, int64(r.Arg0)) + evt.Params.Append(params.NewDirFD, params.Int64, int64(r.Arg1)) + evt.Params.Append(params.FilePath, params.Path, r.filename()) + evt.Params.Append(params.FileNewPath, params.Path, r.aux()) + evt.Params.Append(params.FileFlags, params.Uint64, r.Flags) + case event.Connect, event.Accept: + appendSockParams(evt, r) + case event.Mmap: + addr := uint64(0) + if r.Retval >= 0 { + addr = uint64(r.Retval) + } + evt.Params.Append(params.MemBaseAddress, params.Address, addr) + evt.Params.Append(params.MemRegionSize, params.Uint64, r.Arg1) + evt.Params.Append(params.MemProtect, params.Uint32, uint32(r.Arg2)) + evt.Params.Append(params.MmapFlags, params.Uint64, r.Flags) + evt.Params.Append(params.FD, params.Int64, int64(r.Arg3)) + evt.Params.Append(params.MmapOffset, params.Uint64, r.Arg0) + case event.ProcessVMRead, event.ProcessVMWrite: + evt.Params.Append(params.TargetProcessID, params.Int64, int64(int32(r.Arg0))) + evt.Params.Append(params.MemBaseAddress, params.Address, r.Arg2) + evt.Params.Append(params.MemRegionSize, params.Uint64, r.Arg3) + evt.Params.Append(params.MmapFlags, params.Uint64, r.Flags) + case event.Kill: + evt.Params.Append(params.TargetProcessID, params.Int64, int64(int32(r.Arg0))) + evt.Params.Append(params.Signal, params.Int32, int32(r.Arg1)) + case event.Ptrace: + evt.Params.Append(params.PtraceRequest, params.Int64, int64(r.Arg0)) + evt.Params.Append(params.TargetProcessID, params.Int64, int64(int32(r.Arg1))) + evt.Params.Append(params.PtraceAddr, params.Address, r.Arg2) + evt.Params.Append(params.PtraceData, params.Uint64, r.Arg3) + case event.Prctl: + evt.Params.Append(params.PrctlOption, params.Int64, int64(r.Arg0)) + } + if r.Truncated != 0 { + evt.Params.Append(params.Truncated, params.Uint32, r.Truncated) + } + return evt +} + +func cString(b []byte) string { + if i := bytes.IndexByte(b, 0); i >= 0 { + b = b[:i] + } + return string(b) +} diff --git a/internal/ebpf/events_test.go b/internal/ebpf/events_test.go new file mode 100644 index 000000000..5fd75dd63 --- /dev/null +++ b/internal/ebpf/events_test.go @@ -0,0 +1,183 @@ +//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 ebpf + +import ( + "bytes" + "encoding/binary" + "encoding/json" + "os" + "path/filepath" + "testing" + + "github.com/rabbitstack/fibratus/pkg/event" + "github.com/rabbitstack/fibratus/pkg/event/params" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestDecodeRawEvent(t *testing.T) { + raw := sampleExecve() + buf := encodeRaw(t, raw) + got, err := decodeRawEvent(buf) + require.NoError(t, err) + assert.Equal(t, raw.Type, got.Type) + assert.Equal(t, raw.PID, got.PID) + assert.Equal(t, raw.StartBootTime, got.StartBootTime) + assert.Equal(t, "bash", got.comm()) + assert.Equal(t, "/bin/bash", got.filename()) +} + +func TestRawEventToEventGolden(t *testing.T) { + evt := sampleExecve().toEvent() + evt.Seq = 7 + got := goldenEvent(evt) + path := filepath.Join("testdata", "execve.json") + if os.Getenv("UPDATE_GOLDEN") == "1" { + require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o755)) + require.NoError(t, os.WriteFile(path, prettyJSON(t, got), 0o644)) + } + want, err := os.ReadFile(path) + require.NoError(t, err) + assert.JSONEq(t, string(want), string(prettyJSON(t, got))) +} + +func TestCloneThreadSemantics(t *testing.T) { + raw := sampleClone(0x00010000) + evt := raw.toEvent() + assert.True(t, evt.IsCreateThread()) + assert.False(t, evt.IsCreateProcess()) + + raw = sampleClone(0) + evt = raw.toEvent() + assert.True(t, evt.IsCreateProcess()) + assert.False(t, evt.IsCreateThread()) +} + +func sampleExecve() rawEvent { + var ev rawEvent + ev.Type = uint32(event.Execve) + ev.PID = 4242 + ev.TID = 4242 + ev.TGID = 4242 + ev.PPID = 1 + ev.UID = 1000 + ev.GID = 1000 + ev.SyscallID = 59 + ev.Retval = 0 + ev.StartBootTime = 123456789 + ev.TimestampNs = 111 + copy(ev.Comm[:], "bash") + copy(ev.Filename[:], "/bin/bash") + return ev +} + +func sampleClone(flags uint64) rawEvent { + var ev rawEvent + ev.Type = uint32(event.Clone) + ev.PID = 99 + ev.TID = 100 + ev.TGID = 99 + ev.PPID = 1 + ev.Retval = 99 + ev.Flags = flags + ev.StartBootTime = 55 + copy(ev.Comm[:], "worker") + return ev +} + +func encodeRaw(t *testing.T, ev rawEvent) []byte { + t.Helper() + var buf bytes.Buffer + require.NoError(t, binary.Write(&buf, binary.LittleEndian, ev)) + return buf.Bytes() +} + +type golden struct { + Name string `json:"name"` + PID uint32 `json:"pid"` + Tid uint32 `json:"tid"` + Seq uint64 `json:"seq"` + Params map[string]string `json:"params"` +} + +func goldenEvent(evt *event.Event) golden { + g := golden{ + PID: evt.PID, + Tid: evt.Tid, + Seq: evt.Seq, + Params: map[string]string{}, + } + for name := range evt.Params { + g.Params[name] = evt.GetParamAsString(name) + } + return g +} + +func prettyJSON(t *testing.T, v any) []byte { + t.Helper() + buf, err := json.MarshalIndent(v, "", " ") + require.NoError(t, err) + return append(buf, '\n') +} + +func TestSucceededHelper(t *testing.T) { + evt := sampleExecve().toEvent() + assert.True(t, succeeded(evt)) + evt.Params.Append(params.Retval, params.Int64, int64(-2)) + assert.False(t, succeeded(evt)) +} + +// The first argument of kill is a pid_t whose sign selects the scope of the +// signal, so it must survive the conversion to an event parameter. +func TestSignalTargetKeepsPidSign(t *testing.T) { + var tests = []struct { + name string + arg0 uint64 + want int64 + }{ + {"single process", 4242, 4242}, + {"caller process group", 0, 0}, + {"every permitted process", uint64(^uint32(0)), -1}, + {"process group", uint64(uint32(0xFFFFEF6E)), -4242}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + evt := rawEvent{Type: uint32(event.Kill), Arg0: tt.arg0, Arg1: 9}.toEvent() + target, err := evt.Params.GetInt64(params.TargetProcessID) + require.NoError(t, err) + assert.Equal(t, tt.want, target) + }) + } +} + +func TestPtraceAndProcessVMTargetsAreSigned(t *testing.T) { + ptrace := rawEvent{Type: uint32(event.Ptrace), Arg0: 16, Arg1: 4242}.toEvent() + target, err := ptrace.Params.GetInt64(params.TargetProcessID) + require.NoError(t, err) + assert.Equal(t, int64(4242), target) + + vmread := rawEvent{Type: uint32(event.ProcessVMRead), Arg0: 4242}.toEvent() + target, err = vmread.Params.GetInt64(params.TargetProcessID) + require.NoError(t, err) + assert.Equal(t, int64(4242), target) +} diff --git a/internal/ebpf/features.go b/internal/ebpf/features.go new file mode 100644 index 000000000..d350449f2 --- /dev/null +++ b/internal/ebpf/features.go @@ -0,0 +1,169 @@ +//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 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 + } + + // 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 { + 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..0ea741b66 --- /dev/null +++ b/internal/ebpf/features_test.go @@ -0,0 +1,43 @@ +//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 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/loader.go b/internal/ebpf/loader.go new file mode 100644 index 000000000..cb7ea0af1 --- /dev/null +++ b/internal/ebpf/loader.go @@ -0,0 +1,427 @@ +//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 ebpf + +import ( + "errors" + "fmt" + "io" + "os" + "strings" + "sync" + + "github.com/cilium/ebpf" + "github.com/cilium/ebpf/link" + "github.com/cilium/ebpf/rlimit" + "github.com/rabbitstack/fibratus/internal/ebpf/bpf" + "github.com/rabbitstack/fibratus/pkg/config" + "github.com/rabbitstack/fibratus/pkg/event" + log "github.com/sirupsen/logrus" + "golang.org/x/sys/unix" +) + +type loader struct { + exec *bpf.ExecveObjects + exit *bpf.ExitObjects + clone *bpf.CloneObjects + iter *bpf.ProciterObjects + file *bpf.FileObjects + net *bpf.NetObjects + mem *bpf.MemObjects + ctl *bpf.CtlObjects + links []link.Link + iterLink *link.Iter + once sync.Once +} + +func loadCollections() (*loader, error) { + if err := rlimit.RemoveMemlock(); err != nil { + return nil, fmt.Errorf("removing memlock: %w", err) + } + + execSpec, err := bpf.LoadExecve() + if err != nil { + return nil, fmt.Errorf("loading execve collection spec: %w", err) + } + exitSpec, err := bpf.LoadExit() + if err != nil { + return nil, fmt.Errorf("loading exit collection spec: %w", err) + } + cloneSpec, err := bpf.LoadClone() + if err != nil { + return nil, fmt.Errorf("loading clone collection spec: %w", err) + } + iterSpec, err := bpf.LoadProciter() + if err != nil { + return nil, fmt.Errorf("loading prociter collection spec: %w", err) + } + fileSpec, err := bpf.LoadFile() + if err != nil { + return nil, fmt.Errorf("loading file collection spec: %w", err) + } + netSpec, err := bpf.LoadNet() + if err != nil { + return nil, fmt.Errorf("loading net collection spec: %w", err) + } + memSpec, err := bpf.LoadMem() + if err != nil { + return nil, fmt.Errorf("loading mem collection spec: %w", err) + } + ctlSpec, err := bpf.LoadCtl() + if err != nil { + return nil, fmt.Errorf("loading ctl collection spec: %w", err) + } + + var execObjs bpf.ExecveObjects + if err := execSpec.LoadAndAssign(&execObjs, nil); err != nil { + return nil, fmt.Errorf("loading execve objects: %w", err) + } + + replacements := sharedMaps(&execObjs) + opts := &ebpf.CollectionOptions{MapReplacements: replacements} + + var exitObjs bpf.ExitObjects + if err := exitSpec.LoadAndAssign(&exitObjs, opts); err != nil { + _ = execObjs.Close() + return nil, fmt.Errorf("loading exit objects: %w", err) + } + + var cloneObjs bpf.CloneObjects + if err := cloneSpec.LoadAndAssign(&cloneObjs, opts); err != nil { + _ = exitObjs.Close() + _ = execObjs.Close() + return nil, fmt.Errorf("loading clone objects: %w", err) + } + + var iterObjs bpf.ProciterObjects + if err := iterSpec.LoadAndAssign(&iterObjs, opts); err != nil { + _ = cloneObjs.Close() + _ = exitObjs.Close() + _ = execObjs.Close() + return nil, fmt.Errorf("loading prociter objects: %w", err) + } + + var fileObjs bpf.FileObjects + if err := fileSpec.LoadAndAssign(&fileObjs, opts); err != nil { + _ = iterObjs.Close() + _ = cloneObjs.Close() + _ = exitObjs.Close() + _ = execObjs.Close() + return nil, fmt.Errorf("loading file objects: %w", err) + } + + var netObjs bpf.NetObjects + if err := netSpec.LoadAndAssign(&netObjs, opts); err != nil { + _ = fileObjs.Close() + _ = iterObjs.Close() + _ = cloneObjs.Close() + _ = exitObjs.Close() + _ = execObjs.Close() + return nil, fmt.Errorf("loading net objects: %w", err) + } + + var memObjs bpf.MemObjects + if err := memSpec.LoadAndAssign(&memObjs, opts); err != nil { + _ = netObjs.Close() + _ = fileObjs.Close() + _ = iterObjs.Close() + _ = cloneObjs.Close() + _ = exitObjs.Close() + _ = execObjs.Close() + return nil, fmt.Errorf("loading mem objects: %w", err) + } + + var ctlObjs bpf.CtlObjects + if err := ctlSpec.LoadAndAssign(&ctlObjs, opts); err != nil { + _ = memObjs.Close() + _ = netObjs.Close() + _ = fileObjs.Close() + _ = iterObjs.Close() + _ = cloneObjs.Close() + _ = exitObjs.Close() + _ = execObjs.Close() + return nil, fmt.Errorf("loading ctl objects: %w", err) + } + + return &loader{ + exec: &execObjs, + exit: &exitObjs, + clone: &cloneObjs, + iter: &iterObjs, + file: &fileObjs, + net: &netObjs, + mem: &memObjs, + ctl: &ctlObjs, + }, nil +} + +func (l *loader) eventsMap() *ebpf.Map { return l.exec.Events } + +func (l *loader) dropCount() uint64 { + var key uint32 + var drop uint64 + if l.exec == nil || l.exec.DropCount == nil { + return 0 + } + _ = l.exec.DropCount.Lookup(&key, &drop) + return drop +} + +func (l *loader) setEnabledTypes(cfg *config.EventSourceConfig) error { + if l.exec == nil || l.exec.Enabled == nil { + return fmt.Errorf("missing enabled map") + } + for typ, on := range enabledTypes(cfg) { + key := uint32(typ) + var val uint8 + if on { + val = 1 + } + if err := l.exec.Enabled.Put(&key, &val); err != nil { + return fmt.Errorf("enabling %s: %w", typ, err) + } + } + return nil +} + +func enabledTypes(cfg *config.EventSourceConfig) map[event.Type]bool { + file := cfg == nil || cfg.EnableFileIOEvents + netev := cfg == nil || cfg.EnableNetEvents + mem := cfg == nil || cfg.EnableMemEvents + return map[event.Type]bool{ + event.Execve: true, + event.Exit: true, + event.Clone: true, + event.Kill: true, + event.Ptrace: true, + event.Prctl: true, + event.Openat: file, + event.Unlink: file, + event.Rename: file, + event.Connect: netev, + event.Accept: netev, + event.Mmap: mem, + event.ProcessVMRead: mem, + event.ProcessVMWrite: mem, + } +} + +// syscallsGroup is the tracefs group hosting raw syscall tracepoints. +const syscallsGroup = "syscalls" + +// attachPrograms attaches the live-capture programs: raw syscall tracepoints +// plus the scheduler tp_btf hooks. These feed the ring buffer continuously, +// in contrast to the one-shot iter/task snapshot program started by +// runTaskIterator. The caller starts the ring buffer reader first so no +// events are lost between attachment and consumption. +func (l *loader) attachPrograms(cfg *config.EventSourceConfig) error { + type tp struct { + name string + prog *ebpf.Program + optional bool + } + tracepoints := []tp{ + {"sys_enter_execve", l.exec.HandleSysEnterExecve, false}, + {"sys_exit_execve", l.exec.HandleSysExitExecve, false}, + {"sys_enter_execveat", l.exec.HandleSysEnterExecveat, false}, + {"sys_exit_execveat", l.exec.HandleSysExitExecveat, false}, + {"sys_enter_clone", l.clone.HandleSysEnterClone, false}, + {"sys_exit_clone", l.clone.HandleSysExitClone, false}, + {"sys_enter_clone3", l.clone.HandleSysEnterClone3, false}, + {"sys_exit_clone3", l.clone.HandleSysExitClone3, false}, + // fork/vfork are legacy wrappers. libc uses clone/clone3, and some + // kernels refuse a perf link on these syscall tracepoints. + {"sys_enter_fork", l.clone.HandleSysEnterFork, true}, + {"sys_exit_fork", l.clone.HandleSysExitFork, true}, + {"sys_enter_vfork", l.clone.HandleSysEnterVfork, true}, + {"sys_exit_vfork", l.clone.HandleSysExitVfork, true}, + } + if cfg == nil || cfg.EnableFileIOEvents { + // Legacy variants (open, unlink, rename) follow the fork/vfork + // precedent: some kernels refuse perf links on them. + tracepoints = append(tracepoints, + tp{"sys_enter_open", l.file.HandleSysEnterOpen, true}, + tp{"sys_exit_open", l.file.HandleSysExitOpen, true}, + tp{"sys_enter_openat", l.file.HandleSysEnterOpenat, false}, + tp{"sys_exit_openat", l.file.HandleSysExitOpenat, false}, + tp{"sys_enter_openat2", l.file.HandleSysEnterOpenat2, false}, + tp{"sys_exit_openat2", l.file.HandleSysExitOpenat2, false}, + tp{"sys_enter_unlink", l.file.HandleSysEnterUnlink, true}, + tp{"sys_exit_unlink", l.file.HandleSysExitUnlink, true}, + tp{"sys_enter_unlinkat", l.file.HandleSysEnterUnlinkat, false}, + tp{"sys_exit_unlinkat", l.file.HandleSysExitUnlinkat, false}, + tp{"sys_enter_rename", l.file.HandleSysEnterRename, true}, + tp{"sys_exit_rename", l.file.HandleSysExitRename, true}, + tp{"sys_enter_renameat", l.file.HandleSysEnterRenameat, false}, + tp{"sys_exit_renameat", l.file.HandleSysExitRenameat, false}, + tp{"sys_enter_renameat2", l.file.HandleSysEnterRenameat2, false}, + tp{"sys_exit_renameat2", l.file.HandleSysExitRenameat2, false}, + ) + } + if cfg == nil || cfg.EnableNetEvents { + tracepoints = append(tracepoints, + tp{"sys_enter_connect", l.net.HandleSysEnterConnect, false}, + tp{"sys_exit_connect", l.net.HandleSysExitConnect, false}, + tp{"sys_enter_accept", l.net.HandleSysEnterAccept, false}, + tp{"sys_exit_accept", l.net.HandleSysExitAccept, false}, + tp{"sys_enter_accept4", l.net.HandleSysEnterAccept4, false}, + tp{"sys_exit_accept4", l.net.HandleSysExitAccept4, false}, + ) + } + if cfg == nil || cfg.EnableMemEvents { + tracepoints = append(tracepoints, + tp{"sys_enter_mmap", l.mem.HandleSysEnterMmap, false}, + tp{"sys_exit_mmap", l.mem.HandleSysExitMmap, false}, + tp{"sys_enter_process_vm_readv", l.mem.HandleSysEnterProcessVmReadv, false}, + tp{"sys_exit_process_vm_readv", l.mem.HandleSysExitProcessVmReadv, false}, + tp{"sys_enter_process_vm_writev", l.mem.HandleSysEnterProcessVmWritev, false}, + tp{"sys_exit_process_vm_writev", l.mem.HandleSysExitProcessVmWritev, false}, + ) + } + for _, t := range tracepoints { + if t.prog == nil { + return fmt.Errorf("missing program for %s/%s", syscallsGroup, t.name) + } + lnk, err := link.Tracepoint(syscallsGroup, t.name, t.prog, nil) + if err != nil { + if t.optional && isAttachUnavailable(err) { + log.Warnf("skipping optional %s/%s: %v", syscallsGroup, t.name, err) + continue + } + return fmt.Errorf("attaching %s/%s: %w", syscallsGroup, t.name, err) + } + l.links = append(l.links, lnk) + } + + // Successful clones and process exits are captured from scheduler + // tracepoints. Clone syscall exit tracepoints fire in the parent, and + // exit/exit_group never return, so their exit tracepoints never fire. + // kill/ptrace/prctl read arguments from pt_regs at tp_btf/sys_exit. + tracing := []struct { + name string + prog *ebpf.Program + }{ + {"sched_process_fork", l.clone.HandleSchedProcessFork}, + {"sched_process_exit", l.exit.HandleSchedProcessExit}, + {"sys_exit", l.ctl.HandleSysExit}, + } + for _, t := range tracing { + if t.prog == nil { + return fmt.Errorf("missing %s program", t.name) + } + lnk, err := link.AttachTracing(link.TracingOptions{Program: t.prog}) + if err != nil { + return fmt.Errorf("attaching %s: %w", t.name, err) + } + l.links = append(l.links, lnk) + } + return nil +} + +func isAttachUnavailable(err error) bool { + if err == nil { + return false + } + if errors.Is(err, unix.EPERM) || errors.Is(err, unix.ENOENT) || errors.Is(err, os.ErrPermission) || errors.Is(err, os.ErrNotExist) { + return true + } + msg := strings.ToLower(err.Error()) + return strings.Contains(msg, "permission denied") || strings.Contains(msg, "no such file") +} + +func (l *loader) runTaskIterator() error { + if l.iter == nil || l.iter.DumpTask == nil { + return fmt.Errorf("missing iter/task program") + } + it, err := link.AttachIter(link.IterOptions{Program: l.iter.DumpTask}) + if err != nil { + return fmt.Errorf("attaching iter/task: %w", err) + } + l.iterLink = it + file, err := it.Open() + if err != nil { + return fmt.Errorf("opening task iterator: %w", err) + } + _, _ = io.Copy(io.Discard, file) + return file.Close() +} + +func (l *loader) Close() error { + var err error + l.once.Do(func() { + for _, lnk := range l.links { + if lnk != nil { + if e := lnk.Close(); e != nil { + err = e + } + } + } + if l.iterLink != nil { + if e := l.iterLink.Close(); e != nil { + err = e + } + } + // Replacement collections share maps owned by execve. Close only their + // programs so the canonical maps are released once. + if l.ctl != nil { + if e := l.ctl.CtlPrograms.Close(); e != nil { + err = e + } + } + if l.mem != nil { + if e := l.mem.MemPrograms.Close(); e != nil { + err = e + } + } + if l.net != nil { + if e := l.net.NetPrograms.Close(); e != nil { + err = e + } + } + if l.file != nil { + if e := l.file.FilePrograms.Close(); e != nil { + err = e + } + } + if l.iter != nil { + if e := l.iter.ProciterPrograms.Close(); e != nil { + err = e + } + } + if l.exit != nil { + if e := l.exit.ExitPrograms.Close(); e != nil { + err = e + } + } + if l.clone != nil { + if e := l.clone.ClonePrograms.Close(); e != nil { + err = e + } + } + if l.exec != nil { + if e := l.exec.Close(); e != nil { + err = e + } + } + log.Debug("eBPF loader closed") + }) + return err +} diff --git a/internal/ebpf/loader_test.go b/internal/ebpf/loader_test.go new file mode 100644 index 000000000..443fec4ea --- /dev/null +++ b/internal/ebpf/loader_test.go @@ -0,0 +1,63 @@ +//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 ebpf + +import ( + "errors" + "fmt" + "os" + "testing" + + "github.com/rabbitstack/fibratus/pkg/config" + "github.com/rabbitstack/fibratus/pkg/event" + "github.com/stretchr/testify/assert" + "golang.org/x/sys/unix" +) + +func TestEnabledTypes(t *testing.T) { + all := enabledTypes(nil) + assert.True(t, all[event.Execve]) + assert.True(t, all[event.Openat]) + assert.True(t, all[event.Connect]) + assert.True(t, all[event.Mmap]) + + off := enabledTypes(&config.EventSourceConfig{}) + assert.True(t, off[event.Execve]) + assert.True(t, off[event.Kill]) + assert.False(t, off[event.Openat]) + assert.False(t, off[event.Connect]) + assert.False(t, off[event.Mmap]) + + on := enabledTypes(&config.EventSourceConfig{EnableFileIOEvents: true, EnableNetEvents: true, EnableMemEvents: true}) + assert.True(t, on[event.Openat]) + assert.True(t, on[event.Accept]) + assert.True(t, on[event.ProcessVMRead]) +} + +func TestIsAttachUnavailable(t *testing.T) { + assert.False(t, isAttachUnavailable(nil)) + assert.False(t, isAttachUnavailable(errors.New("verifier rejected"))) + assert.True(t, isAttachUnavailable(unix.EPERM)) + assert.True(t, isAttachUnavailable(unix.ENOENT)) + assert.True(t, isAttachUnavailable(os.ErrPermission)) + assert.True(t, isAttachUnavailable(fmt.Errorf("attaching syscalls/sys_enter_fork: cannot create bpf perf link: %w", unix.EPERM))) + assert.True(t, isAttachUnavailable(errors.New("cannot create bpf perf link: permission denied"))) +} diff --git a/internal/ebpf/maps.go b/internal/ebpf/maps.go new file mode 100644 index 000000000..51f129b46 --- /dev/null +++ b/internal/ebpf/maps.go @@ -0,0 +1,48 @@ +//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 ebpf + +const ( + eventsMapName = "events" + dropCountMapName = "drop_count" + scratchMapName = "scratch" + scratchHeapMapName = "scratch_heap" + enabledMapName = "enabled" + approverGenMapName = "approver_gen" + approverModeMapName = "approver_mode" + approverPIDMapName = "approver_pid" + approverPortMapName = "approver_port" + approverFileEqMapName = "approver_file_eq" + approverFilePre0Name = "approver_file_pre_0" + approverFilePre1Name = "approver_file_pre_1" + approverFileHeapName = "approver_file_heap" + approverLPMHeapName = "approver_lpm_heap" + approverRejectMapName = "approver_reject" +) + +// Mirrors APPR_REQ_* and EVT_TYPE_MAX in c/common/approvers.h. Both sides index +// the mode array as generation*approverTypeMax+type, so the values must agree. +const ( + approverReqPID = 1 << 0 + approverReqFile = 1 << 1 + approverReqPort = 1 << 2 + approverTypeMax = 32 +) diff --git a/internal/ebpf/matrix_test.go b/internal/ebpf/matrix_test.go new file mode 100644 index 000000000..de4904281 --- /dev/null +++ b/internal/ebpf/matrix_test.go @@ -0,0 +1,159 @@ +//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 ebpf + +import ( + "testing" + + "github.com/rabbitstack/fibratus/pkg/event" + "github.com/rabbitstack/fibratus/pkg/event/params" + "github.com/rabbitstack/fibratus/pkg/ps" + pstypes "github.com/rabbitstack/fibratus/pkg/ps/types" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "golang.org/x/sys/unix" +) + +type matrixRow struct { + name string + typ event.Type + syscalls []string + hook string + params []string +} + +const hookSyscallIO = "tp/syscalls enter/exit" + +func syscallMatrix() []matrixRow { + return []matrixRow{ + {"execve", event.Execve, []string{"execve", "execveat"}, hookSyscallIO, []string{params.Exe, params.Retval}}, + {"exit", event.Exit, []string{"sched_process_exit"}, "tp_btf/sched_process_exit", []string{params.ExitStatus}}, + {"clone", event.Clone, []string{"clone", "clone3", "fork", "vfork"}, "tp/syscalls + tp_btf/sched_process_fork", []string{params.CloneFlags}}, + {"openat", event.Openat, []string{"open", "openat", "openat2"}, hookSyscallIO, []string{params.FilePath, params.DirFD, params.FileFlags, params.Retval}}, + {"unlink", event.Unlink, []string{"unlink", "unlinkat"}, hookSyscallIO, []string{params.FilePath, params.DirFD, params.Retval}}, + {"rename", event.Rename, []string{"rename", "renameat", "renameat2"}, hookSyscallIO, []string{params.FilePath, params.FileNewPath, params.Retval}}, + {"connect", event.Connect, []string{"connect"}, "tp/syscalls enter/exit; sockaddr copied at enter", []string{params.FD, params.SockFamily, params.Retval}}, + {"accept", event.Accept, []string{"accept", "accept4"}, "tp/syscalls enter/exit; sockaddr copied at exit", []string{params.FD, params.SockFamily, params.Retval}}, + {"mmap", event.Mmap, []string{"mmap"}, hookSyscallIO, []string{params.MemBaseAddress, params.MemRegionSize, params.MemProtect, params.MmapFlags, params.Retval}}, + {"process_vm_readv", event.ProcessVMRead, []string{"process_vm_readv"}, "tp/syscalls enter/exit; first remote iovec only", []string{params.TargetProcessID, params.MemBaseAddress, params.Retval}}, + {"process_vm_writev", event.ProcessVMWrite, []string{"process_vm_writev"}, "tp/syscalls enter/exit; first remote iovec only", []string{params.TargetProcessID, params.MemBaseAddress, params.Retval}}, + {"kill", event.Kill, []string{"kill", "tkill", "tgkill"}, "tp_btf/sys_exit", []string{params.TargetProcessID, params.Signal, params.Retval}}, + {"ptrace", event.Ptrace, []string{"ptrace"}, "tp_btf/sys_exit", []string{params.PtraceRequest, params.TargetProcessID, params.Retval}}, + {"prctl", event.Prctl, []string{"prctl"}, "tp_btf/sys_exit", []string{params.PrctlOption, params.Retval}}, + } +} + +func TestSyscallEventMatrix(t *testing.T) { + seen := map[event.Type]bool{} + for _, row := range syscallMatrix() { + assert.Equal(t, row.name, row.typ.String()) + assert.NotEmpty(t, row.syscalls) + assert.NotEmpty(t, row.hook) + seen[row.typ] = true + raw := rawEvent{Type: uint32(row.typ), Retval: 0, Filename: [256]byte{'/'}, Aux: [256]byte{'/'}} + if row.typ == event.Connect || row.typ == event.Accept { + raw.Aux[0] = byte(unix.AF_INET) + raw.Aux[1] = 0 + raw.Aux[2] = 0 + raw.Aux[3] = 80 + raw.Aux[4] = 127 + raw.Aux[5] = 0 + raw.Aux[6] = 0 + raw.Aux[7] = 1 + } + evt := raw.toEvent() + require.Equal(t, row.typ, evt.Type, row.name) + for _, name := range row.params { + _, err := evt.Params.Get(name) + assert.NoErrorf(t, err, "%s missing param %s", row.name, name) + } + } + for _, typ := range event.AllTypes() { + assert.Truef(t, seen[typ], "event type %s missing from the syscall matrix", typ) + } +} + +func TestParseSockaddr(t *testing.T) { + var inet [256]byte + inet[0] = byte(unix.AF_INET) + inet[2] = 0x00 + inet[3] = 0x50 + inet[4] = 10 + inet[5] = 1 + inet[6] = 2 + inet[7] = 3 + family, ip, port, unixPath := parseSockaddr(inet[:]) + assert.Equal(t, uint16(unix.AF_INET), family) + assert.Equal(t, "10.1.2.3", ip.String()) + assert.Equal(t, uint16(80), port) + assert.Empty(t, unixPath) + + var un [256]byte + un[0] = byte(unix.AF_UNIX) + copy(un[2:], "/tmp/fibratus.sock") + family, ip, port, unixPath = parseSockaddr(un[:]) + assert.Equal(t, uint16(unix.AF_UNIX), family) + assert.Nil(t, ip) + assert.Equal(t, "/tmp/fibratus.sock", unixPath) + assert.Zero(t, port) +} + +func TestMmapUpdatesProcessState(t *testing.T) { + snap := ps.NewSnapshotter() + ps := &pstypes.PS{PID: 9, Name: "target", StartBootTime: 1, Threads: map[uint32]pstypes.Thread{}} + snap.Put(ps) + + raw := rawEvent{Type: uint32(event.Mmap), PID: 9, TGID: 9, Retval: 0x1000, Arg0: 4096, Arg1: 8192, Arg2: 3, Arg3: 3, Flags: 0} + evt := raw.toEvent() + applyProcessState(snap, evt) + ok, got := snap.Find(9) + require.True(t, ok) + require.Len(t, got.Mmaps, 1) + assert.Equal(t, uint64(0x1000), uint64(got.Mmaps[0].BaseAddress)) + assert.Equal(t, uint64(8192), got.Mmaps[0].Size) + assert.Equal(t, "file", got.Mmaps[0].Type) +} + +func TestAnonymousMmapSkipped(t *testing.T) { + snap := ps.NewSnapshotter() + ps := &pstypes.PS{PID: 9, Name: "target", StartBootTime: 1, Threads: map[uint32]pstypes.Thread{}} + snap.Put(ps) + + raw := rawEvent{Type: uint32(event.Mmap), PID: 9, TGID: 9, Retval: 0x1000, Arg1: 8192, Arg2: 3, Arg3: ^uint64(0), Flags: 0x20} + evt := raw.toEvent() + applyProcessState(snap, evt) + ok, got := snap.Find(9) + require.True(t, ok) + assert.Empty(t, got.Mmaps) +} + +func TestFailedSyscallKeepsProcessState(t *testing.T) { + snap := ps.NewSnapshotter() + snap.Put(&pstypes.PS{PID: 11, Name: "keep", StartBootTime: 4}) + raw := rawEvent{Type: uint32(event.Openat), PID: 11, TGID: 11, Retval: -2} + copy(raw.Filename[:], "/no/such") + evt := raw.toEvent() + applyProcessState(snap, evt) + ok, got := snap.Find(11) + require.True(t, ok) + assert.Equal(t, "keep", got.Name) + assert.Empty(t, got.Mmaps) +} diff --git a/internal/ebpf/net.go b/internal/ebpf/net.go new file mode 100644 index 000000000..6d9d50ba4 --- /dev/null +++ b/internal/ebpf/net.go @@ -0,0 +1,85 @@ +//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 ebpf + +import ( + "encoding/binary" + "net" + + "github.com/rabbitstack/fibratus/pkg/event" + "github.com/rabbitstack/fibratus/pkg/event/params" + "golang.org/x/sys/unix" +) + +func appendSockParams(evt *event.Event, r rawEvent) { + evt.Params.Append(params.FD, params.Int64, int64(r.Arg0)) + if r.Type == uint32(event.Accept) && r.Retval >= 0 { + evt.Params.Append(params.NewFD, params.Int64, r.Retval) + } + if r.Flags != 0 { + evt.Params.Append(params.SockFlags, params.Uint64, r.Flags) + } + + family, ip, port, unixPath := parseSockaddr(r.Aux[:]) + evt.Params.Append(params.SockFamily, params.Uint16, family) + if unixPath != "" { + evt.Params.Append(params.SockPath, params.Path, unixPath) + return + } + if ip == nil { + return + } + ipParam := params.IPv4 + if ip.To4() == nil { + ipParam = params.IPv6 + } + if r.Type == uint32(event.Connect) { + evt.Params.Append(params.NetDIP, ipParam, ip) + evt.Params.Append(params.NetDport, params.Port, port) + return + } + evt.Params.Append(params.NetSIP, ipParam, ip) + evt.Params.Append(params.NetSport, params.Port, port) +} + +func parseSockaddr(b []byte) (family uint16, ip net.IP, port uint16, unixPath string) { + if len(b) < 2 { + return 0, nil, 0, "" + } + family = binary.LittleEndian.Uint16(b[0:2]) + switch family { + case unix.AF_INET: + if len(b) >= 8 { + port = binary.BigEndian.Uint16(b[2:4]) + ip = net.IPv4(b[4], b[5], b[6], b[7]).To4() + } + case unix.AF_INET6: + if len(b) >= 24 { + port = binary.BigEndian.Uint16(b[2:4]) + ip = net.IP(append([]byte(nil), b[8:24]...)) + } + case unix.AF_UNIX: + if len(b) > 2 { + unixPath = cString(b[2:]) + } + } + return family, ip, port, unixPath +} diff --git a/internal/ebpf/prerequisites_integration_test.go b/internal/ebpf/prerequisites_integration_test.go new file mode 100644 index 000000000..3a7a8e755 --- /dev/null +++ b/internal/ebpf/prerequisites_integration_test.go @@ -0,0 +1,49 @@ +//go:build linux && ebpf_integration + +/* + * 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 ebpf + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +// TestPrerequisitesAreMet asserts the host satisfies the runtime contract +// instead of skipping when it does not. A runner that silently loses runtime +// BTF, or drops below the kernel floor, would otherwise report a green suite +// that never loaded a program. It runs the same gate Open does, so the arch +// check is covered too. +func TestPrerequisitesAreMet(t *testing.T) { + report, err := checkRuntimeSupport() + if report != nil { + t.Logf("kernel=%s (ok=%v, floor=%s) btf=%s (ok=%v) ringbuf=%v ringbuf_helper=%v tracing=%v iter=%v", + report.KernelRelease, report.KernelOK, MinKernelVersion, + report.BTFPath, report.BTFOK, + report.RingbufOK, report.RingbufHelper, report.TracingOK, report.IterOK) + } + require.NoError(t, err, "host does not meet the Linux eBPF runtime contract") + require.NotNil(t, report) + require.True(t, report.KernelOK) + require.True(t, report.BTFOK) + require.True(t, report.RingbufOK) + require.True(t, report.TracingOK) + require.True(t, report.IterOK) +} diff --git a/internal/ebpf/proc_iter.go b/internal/ebpf/proc_iter.go new file mode 100644 index 000000000..698044034 --- /dev/null +++ b/internal/ebpf/proc_iter.go @@ -0,0 +1,64 @@ +//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 ebpf + +import ( + "strings" + + pstypes "github.com/rabbitstack/fibratus/pkg/ps/types" +) + +func snapshotFromRaw(r rawEvent, exe, cmdline string) *pstypes.PS { + name := r.comm() + if name == "" && exe != "" { + name = baseName(exe) + } + if cmdline == "" { + cmdline = exe + } + args := splitCmdline(cmdline) + return &pstypes.PS{ + PID: r.TGID, + Ppid: r.PPID, + Name: name, + Cmdline: cmdline, + Exe: exe, + Args: args, + StartBootTime: r.StartBootTime, + UID: r.UID, + GID: r.GID, + Threads: make(map[uint32]pstypes.Thread), + } +} + +func baseName(path string) string { + if i := strings.LastIndex(path, "/"); i >= 0 && i+1 < len(path) { + return path[i+1:] + } + return path +} + +func splitCmdline(cmdline string) []string { + if cmdline == "" { + return nil + } + return strings.Fields(cmdline) +} diff --git a/internal/ebpf/reconcile.go b/internal/ebpf/reconcile.go new file mode 100644 index 000000000..072ae26e5 --- /dev/null +++ b/internal/ebpf/reconcile.go @@ -0,0 +1,228 @@ +/* + * 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 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. +// 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 { + 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..cc20817b4 --- /dev/null +++ b/internal/ebpf/reconcile_test.go @@ -0,0 +1,103 @@ +/* + * 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 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 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} + 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()) + } +} diff --git a/internal/ebpf/ringbuf.go b/internal/ebpf/ringbuf.go new file mode 100644 index 000000000..fd9b0d488 --- /dev/null +++ b/internal/ebpf/ringbuf.go @@ -0,0 +1,60 @@ +//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 ebpf + +import ( + "errors" + "fmt" + + "github.com/cilium/ebpf" + "github.com/cilium/ebpf/ringbuf" +) + +type ringReader struct { + rd *ringbuf.Reader +} + +func newRingReader(m *ebpf.Map) (*ringReader, error) { + rd, err := ringbuf.NewReader(m) + if err != nil { + return nil, fmt.Errorf("opening ring buffer: %w", err) + } + return &ringReader{rd: rd}, nil +} + +func (r *ringReader) Read() ([]byte, error) { + record, err := r.rd.Read() + if err != nil { + return nil, err + } + return record.RawSample, nil +} + +func (r *ringReader) Close() error { + if r == nil || r.rd == nil { + return nil + } + return r.rd.Close() +} + +func isRingClosed(err error) bool { + return errors.Is(err, ringbuf.ErrClosed) +} diff --git a/internal/ebpf/source.go b/internal/ebpf/source.go new file mode 100644 index 000000000..ef9aeff8e --- /dev/null +++ b/internal/ebpf/source.go @@ -0,0 +1,345 @@ +//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 ebpf + +import ( + "fmt" + "sync" + "sync/atomic" + "time" + + "github.com/rabbitstack/fibratus/pkg/config" + "github.com/rabbitstack/fibratus/pkg/event" + "github.com/rabbitstack/fibratus/pkg/filter" + "github.com/rabbitstack/fibratus/pkg/ps" + "github.com/rabbitstack/fibratus/pkg/source" + log "github.com/sirupsen/logrus" +) + +const ( + defaultPendingCap = 4096 + startupDrain = 250 * time.Millisecond +) + +var _ source.EventSource = (*EventSource)(nil) + +// EventSource captures Linux process events through eBPF. +type EventSource struct { + psnap ps.Snapshotter + config *config.Config + sequencer *event.Sequencer + q *event.Queue + evts chan *event.Event + errs chan error + + filter filter.Filter + rulesPlan *filter.ApproverPlan + cliPlan *filter.ApproverPlan + approverMu sync.Mutex + listeners []event.Listener + + loader *loader + reader *ringReader + + pending []*event.Event + pendingMu sync.Mutex + pendingCap int + live atomic.Bool + + stop chan struct{} + done chan struct{} + once sync.Once +} + +// NewEventSource constructs the Linux eBPF event source. +func NewEventSource(psnap ps.Snapshotter, cfg *config.Config, _ *config.RulesCompileResult, plan *filter.ApproverPlan) source.EventSource { + evts := make(chan *event.Event, defaultPendingCap) + return &EventSource{ + psnap: psnap, + config: cfg, + sequencer: event.NewSequencer(), + evts: evts, + q: event.NewQueueWithChannel(evts, false, cfg.ForwardMode), + errs: make(chan error, 256), + listeners: make([]event.Listener, 0), + pendingCap: defaultPendingCap, + stop: make(chan struct{}), + done: make(chan struct{}), + rulesPlan: plan, + } +} + +func (e *EventSource) Open(cfg *config.Config) error { + if cfg != nil { + e.config = cfg + } + if e.config == nil { + return fmt.Errorf("missing configuration") + } + + report, err := checkRuntimeSupport() + if err != nil { + if report != nil { + return fmt.Errorf("eBPF prerequisites: %w", err) + } + return err + } + log.Infof("eBPF prerequisites ok: kernel=%s btf=%s ringbuf=%v iter=%v", + report.KernelRelease, report.BTFPath, report.RingbufOK, report.IterOK) + + ldr, err := loadCollections() + if err != nil { + return err + } + e.loader = ldr + + if err := ldr.setEnabledTypes(&e.config.EventSource); err != nil { + _ = ldr.Close() + e.loader = nil + return err + } + if err := e.reloadApprovers(); err != nil { + log.Warnf("approver population failed, default-allow: %v", err) + } + + rd, err := newRingReader(ldr.eventsMap()) + if err != nil { + _ = ldr.Close() + return err + } + e.reader = rd + + go e.consume() + + if err := ldr.attachPrograms(&e.config.EventSource); err != nil { + e.Close() + return err + } + + if err := ldr.runTaskIterator(); err != nil { + e.Close() + return err + } + + time.Sleep(startupDrain) + e.finishBaseline() + e.sampleCounters() + log.Infof("eBPF process source is live; %s", e.startupSummary()) + return nil +} + +// sampleCounters mirrors the cumulative kernel-side counters into expvars. The +// maps hold running totals, so this reads them rather than accumulating. +func (e *EventSource) sampleCounters() { + if e.loader == nil { + return + } + ringbufDrops.Set(int64(e.loader.dropCount())) + approverDrops.Set(int64(e.loader.approverRejects())) +} + +func (e *EventSource) Close() error { + var err error + e.once.Do(func() { + close(e.stop) + started := e.reader != nil + if e.reader != nil { + _ = e.reader.Close() + } + if e.loader != nil { + e.sampleCounters() + err = e.loader.Close() + } + if started { + <-e.done + } + if e.sequencer != nil { + _ = e.sequencer.Shutdown() + } + if e.q != nil { + e.q.Close() + } + }) + return err +} + +func (e *EventSource) Errors() <-chan error { return e.errs } + +func (e *EventSource) Events() <-chan *event.Event { return e.q.Events() } + +func (e *EventSource) SetFilter(f filter.Filter) { + e.filter = f + e.approverMu.Lock() + e.cliPlan = filter.PlanFromFilter(f) + e.approverMu.Unlock() + if err := e.reloadApprovers(); err != nil { + log.Warnf("approver reload failed, keeping previous policy: %v", err) + } +} + +func (e *EventSource) reloadApprovers() error { + e.approverMu.Lock() + defer e.approverMu.Unlock() + if e.loader == nil { + return nil + } + return e.loader.populateApprovers(filter.Union(e.rulesPlan, e.cliPlan)) +} + +func (e *EventSource) RegisterEventListener(lis event.Listener) { + e.listeners = append(e.listeners, lis) + if e.q != nil { + e.q.RegisterListener(lis) + } +} + +func (e *EventSource) consume() { + defer close(e.done) + for { + raw, err := e.reader.Read() + if err != nil { + if isRingClosed(err) { + return + } + select { + case <-e.stop: + return + case e.errs <- err: + default: + } + continue + } + e.handleRecord(raw) + } +} + +func (e *EventSource) handleRecord(raw []byte) { + rec, err := decodeRawEvent(raw) + if err != nil { + parseErrors.Add(1) + return + } + if rec.Type == snapshotType { + e.handleSnapshot(rec) + return + } + typ := rec.eventType() + if typ == event.Unknown { + eventsUnknown.Add(1) + return + } + + evt := rec.toEvent() + if typ == event.Execve || typ == event.Clone { + enrichEvent(evt) + } + + if !e.live.Load() && e.enqueuePending(evt) { + return + } + e.dispatch(evt) +} + +func (e *EventSource) handleSnapshot(rec rawEvent) { + if e.live.Load() { + lateSnapshots.Add(1) + return + } + exe, cmdline, err := enrichFromProc(rec.TGID) + if err != nil { + enrichmentMiss.Add(1) + } + upsertSnapshot(e.psnap, snapshotFromRaw(rec, exe, cmdline)) +} + +func (e *EventSource) enqueuePending(evt *event.Event) bool { + e.pendingMu.Lock() + defer e.pendingMu.Unlock() + if e.live.Load() { + return false + } + if len(e.pending) >= e.pendingCap { + pendingDropped.Add(1) + return false + } + e.pending = append(e.pending, evt) + pendingQueued.Add(1) + return true +} + +// finishBaseline replays queued hot events in ring-buffer order and then +// switches to live dispatch. New records keep landing in the pending queue +// while a replay round runs, so loop until the queue drains before flipping +// live. This guarantees replayed and live events preserve global ring-buffer +// order. +func (e *EventSource) finishBaseline() { + for { + e.pendingMu.Lock() + pending := e.pending + e.pending = nil + if len(pending) == 0 { + e.live.Store(true) + e.pendingMu.Unlock() + return + } + e.pendingMu.Unlock() + for _, evt := range pending { + e.dispatch(evt) + replayApplied.Add(1) + } + } +} + +func (e *EventSource) dispatch(evt *event.Event) { + evt.Seq = e.sequencer.Get() + applyProcessState(e.psnap, evt) + eventsProcessed.Add(1) + + if e.config != nil { + if e.config.EventSource.ExcludeEvent(evt.Type) { + eventsExcluded.Add(1) + return + } + if e.config.EventSource.ExcludeProcess(evt.PS) { + eventsExcluded.Add(1) + return + } + if evt.IsDropped(e.config.IsCaptureSet()) { + eventsExcluded.Add(1) + return + } + } + if e.filter != nil && !e.filter.Eval(evt) { + return + } + e.sequencer.Increment() + if err := e.q.Push(evt); err != nil { + select { + case e.errs <- err: + default: + } + } +} + +func (e *EventSource) startupSummary() string { + return fmt.Sprintf("pending_queued=%d pending_dropped=%d replay_applied=%d snapshot_upserts=%d approver_drops=%d", + pendingQueued.Value(), pendingDropped.Value(), replayApplied.Value(), snapshotUpserts.Value(), approverDrops.Value()) +} diff --git a/internal/ebpf/source_integration_test.go b/internal/ebpf/source_integration_test.go new file mode 100644 index 000000000..59e5b654b --- /dev/null +++ b/internal/ebpf/source_integration_test.go @@ -0,0 +1,127 @@ +//go:build linux && ebpf_integration + +/* + * 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 ebpf + +import ( + "os" + "os/exec" + "path/filepath" + "testing" + "time" + + "github.com/rabbitstack/fibratus/pkg/event" + "github.com/rabbitstack/fibratus/pkg/ps" + "github.com/stretchr/testify/require" +) + +func TestLiveProcessSource(t *testing.T) { + cfg := testConfig() + es := NewEventSource(ps.NewSnapshotter(), cfg, nil, nil).(*EventSource) + if err := es.Open(cfg); err != nil { + t.Fatalf("opening process source: %v", err) + } + t.Cleanup(func() { _ = es.Close() }) + + cmd := execLookPath() + p, err := os.StartProcess(cmd, []string{cmd}, &os.ProcAttr{ + Files: []*os.File{nil, nil, nil}, + }) + require.NoError(t, err) + _, _ = p.Wait() + + deadline := time.Now().Add(5 * time.Second) + var sawExec, sawExit bool + for time.Now().Before(deadline) && (!sawExec || !sawExit) { + select { + case evt := <-es.Events(): + switch evt.Type { + case event.Execve: + if evt.PID == uint64(p.Pid) { + sawExec = true + } + case event.Exit: + if evt.PID == uint64(p.Pid) { + sawExit = true + } + } + case err := <-es.Errors(): + t.Fatalf("event source error: %v", err) + case <-time.After(50 * time.Millisecond): + } + } + if !sawExec { + t.Fatal("did not observe execve for spawned process") + } + if !sawExit { + t.Fatal("did not observe exit for spawned process") + } +} + +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 TestLiveSyscallTelemetry(t *testing.T) { + cfg := testConfig() + es := NewEventSource(ps.NewSnapshotter(), cfg, nil, nil).(*EventSource) + if err := es.Open(cfg); err != nil { + t.Fatalf("opening process source: %v", err) + } + t.Cleanup(func() { _ = es.Close() }) + + dir := t.TempDir() + path := filepath.Join(dir, "x") + script := "echo hi > \"$1\" && mv \"$1\" \"$1.new\" && rm -f \"$1.new\" && kill -0 $$" + cmd := exec.Command("/bin/sh", "-c", script, "sh", path) + require.NoError(t, cmd.Run()) + + deadline := time.Now().Add(5 * time.Second) + saw := map[event.Type]bool{} + for time.Now().Before(deadline) && (!saw[event.Openat] || !saw[event.Rename] || !saw[event.Unlink] || !saw[event.Kill]) { + select { + case evt := <-es.Events(): + switch evt.Type { + case event.Openat, event.Rename, event.Unlink, event.Kill, event.Mmap: + saw[evt.Type] = true + } + case err := <-es.Errors(): + t.Fatalf("event source error: %v", err) + case <-time.After(50 * time.Millisecond): + } + } + if !saw[event.Openat] { + t.Fatal("did not observe openat") + } + if !saw[event.Rename] { + t.Fatal("did not observe rename") + } + if !saw[event.Unlink] { + t.Fatal("did not observe unlink") + } + if !saw[event.Kill] { + t.Fatal("did not observe kill") + } +} diff --git a/internal/ebpf/source_test.go b/internal/ebpf/source_test.go new file mode 100644 index 000000000..3503c79b6 --- /dev/null +++ b/internal/ebpf/source_test.go @@ -0,0 +1,121 @@ +//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 ebpf + +import ( + "testing" + + "github.com/rabbitstack/fibratus/pkg/config" + "github.com/rabbitstack/fibratus/pkg/event" + "github.com/rabbitstack/fibratus/pkg/ps" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func testConfig() *config.Config { + cfg := &config.Config{ForwardMode: true} + cfg.EventSource.EnableFileIOEvents = true + cfg.EventSource.EnableNetEvents = true + cfg.EventSource.EnableMemEvents = true + cfg.EventSource.Init() + cfg.Filters = &config.Filters{} + return cfg +} + +func TestStartupReplayAndLateSnapshot(t *testing.T) { + cfg := testConfig() + es := NewEventSource(ps.NewSnapshotter(), cfg, nil, nil).(*EventSource) + + hot := sampleExecve() + hot.PID = 42 + hot.TGID = 42 + hot.StartBootTime = 100 + hot.Comm = [16]byte{} + hot.Filename = [256]byte{} + copy(hot.Comm[:], "hot-a") + copy(hot.Filename[:], "/bin/hot-a") + es.handleRecord(encodeRaw(t, hot)) + require.Len(t, es.pending, 1) + ok, _ := es.psnap.Find(42) + assert.False(t, ok) + + snap := hot + snap.Type = snapshotType + snap.Comm = [16]byte{} + copy(snap.Comm[:], "snap-a") + es.handleSnapshot(snap) + ok, got := es.psnap.Find(42) + require.True(t, ok) + assert.Equal(t, "snap-a", got.Name) + + es.finishBaseline() + assert.True(t, es.live.Load()) + assert.Nil(t, es.pending) + + select { + case evt := <-es.Events(): + assert.Equal(t, event.Execve, evt.Type) + assert.Equal(t, uint64(42), evt.PID) + require.NotNil(t, evt.PS) + assert.Equal(t, "hot-a", evt.PS.Name) + assert.Equal(t, uint64(100), evt.PS.StartBootTime) + default: + t.Fatal("expected replayed execve on the output queue") + } + + late := snap + late.Comm = [16]byte{} + copy(late.Comm[:], "stale") + es.handleSnapshot(late) + ok, got = es.psnap.Find(42) + require.True(t, ok) + assert.Equal(t, "hot-a", got.Name) +} + +func TestPIDReuseKeepsDistinctUUIDs(t *testing.T) { + cfg := testConfig() + es := NewEventSource(ps.NewSnapshotter(), cfg, nil, nil).(*EventSource) + es.live.Store(true) + + first := sampleExecve() + first.PID = 8 + first.TGID = 8 + first.StartBootTime = 1 + first.Comm = [16]byte{} + copy(first.Comm[:], "one") + es.handleRecord(encodeRaw(t, first)) + + exit := rawEvent{Type: uint32(event.Exit), PID: 8, TGID: 8, StartBootTime: 1} + es.handleRecord(encodeRaw(t, exit)) + + second := first + second.StartBootTime = 2 + second.Comm = [16]byte{} + second.Filename = [256]byte{} + copy(second.Comm[:], "two") + copy(second.Filename[:], "/bin/two") + es.handleRecord(encodeRaw(t, second)) + + ok, got := es.psnap.Find(8) + require.True(t, ok) + assert.Equal(t, "two", got.Name) + assert.Equal(t, uint64(2), got.StartBootTime) +} 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..c5a3f8ae2 --- /dev/null +++ b/internal/ebpf/spike/c/vmlinux.h @@ -0,0 +1,160 @@ +/* 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 + +/* x86-64 field names from kernel BTF. CO-RE relocates by name. */ +struct pt_regs { + unsigned long r10; + unsigned long r8; + unsigned long dx; + unsigned long si; + unsigned long di; + unsigned long orig_ax; +} __attribute__((preserve_access_index)); + +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; + int exit_code; + 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..46efe842d --- /dev/null +++ b/internal/ebpf/spike/cmd/spike/main.go @@ -0,0 +1,47 @@ +//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 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..9376b8bcf --- /dev/null +++ b/internal/ebpf/spike/enrich.go @@ -0,0 +1,53 @@ +//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 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..f86f5dfac --- /dev/null +++ b/internal/ebpf/spike/event.go @@ -0,0 +1,35 @@ +//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 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 000000000..2619d2236 Binary files /dev/null and b/internal/ebpf/spike/execve_bpfeb.o differ 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 000000000..82e5ffdd8 Binary files /dev/null and b/internal/ebpf/spike/execve_bpfel.o differ diff --git a/internal/ebpf/spike/gen.go b/internal/ebpf/spike/gen.go new file mode 100644 index 000000000..1e9349f1c --- /dev/null +++ b/internal/ebpf/spike/gen.go @@ -0,0 +1,26 @@ +//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 spike + +// Regenerate with ./generate.sh (preferred) or go generate. +// bpf2go version is pinned to github.com/cilium/ebpf v0.20.0. +// +//go:generate ./generate.sh diff --git a/internal/ebpf/spike/generate.sh b/internal/ebpf/spike/generate.sh new file mode 100755 index 000000000..688e13d26 --- /dev/null +++ b/internal/ebpf/spike/generate.sh @@ -0,0 +1,34 @@ +#!/usr/bin/env bash +# Regenerate bpf2go bindings for the Linux eBPF spike. +set -euo pipefail + +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +cd "$ROOT" + +if ! command -v clang >/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 000000000..4547f4feb Binary files /dev/null and b/internal/ebpf/spike/prociter_bpfeb.o differ 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 000000000..08f210f72 Binary files /dev/null and b/internal/ebpf/spike/prociter_bpfel.o differ diff --git a/internal/ebpf/spike/run.go b/internal/ebpf/spike/run.go new file mode 100644 index 000000000..c313bf0ae --- /dev/null +++ b/internal/ebpf/spike/run.go @@ -0,0 +1,295 @@ +//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 spike + +import ( + "bytes" + "encoding/binary" + "errors" + "fmt" + "io" + "os" + "sync/atomic" + "time" + + "github.com/cilium/ebpf" + "github.com/cilium/ebpf/link" + "github.com/cilium/ebpf/ringbuf" + "github.com/cilium/ebpf/rlimit" + libebpf "github.com/rabbitstack/fibratus/internal/ebpf" +) + +const ( + eventKindExec = 1 + eventKindSnapshot = 2 +) + +// Result summarizes a successful spike run. +type Result struct { + Prerequisites *libebpf.PrerequisiteReport + Snapshots int + ExecEvents int + Reconciled int + Metrics string +} + +// 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 := libebpf.ProbePrerequisites() + if err != nil { + return &Result{Prerequisites: report}, fmt.Errorf("prerequisites: %w", err) + } + + if err := rlimit.RemoveMemlock(); err != nil { + return nil, fmt.Errorf("removing memlock: %w", err) + } + + execSpec, err := loadExecve() + if err != nil { + return nil, fmt.Errorf("loading execve collection spec: %w", err) + } + iterSpec, err := loadProciter() + if err != nil { + return nil, fmt.Errorf("loading prociter collection spec: %w", err) + } + + var execObjs execveObjects + if err := execSpec.LoadAndAssign(&execObjs, nil); err != nil { + return nil, fmt.Errorf("loading execve objects: %w", err) + } + 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{ + "events": execObjs.Events, + "drop_count": execObjs.DropCount, + }, + }); err != nil { + return nil, fmt.Errorf("loading prociter with map replacements: %w", err) + } + defer func() { + if iterObjs.DumpTask != nil { + _ = iterObjs.DumpTask.Close() + } + }() + + rd, err := ringbuf.NewReader(execObjs.Events) + if err != nil { + return nil, fmt.Errorf("opening ringbuf reader: %w", err) + } + defer rd.Close() + + reconciler := libebpf.NewStartupReconciler(4096) + stop := make(chan struct{}) + done := make(chan struct{}) + var execCount, snapCount atomic.Uint64 + + go func() { + defer close(done) + for { + record, err := rd.Read() + if err != nil { + if errors.Is(err, ringbuf.ErrClosed) { + return + } + select { + case <-stop: + return + case <-time.After(10 * time.Millisecond): + continue + } + } + ev, err := parseSpikeEvent(record.RawSample) + if err != nil { + continue + } + key := libebpf.ProcessKey{PID: ev.Tgid, StartBootTime: ev.StartBoottime} + comm := cString(ev.Comm[:]) + filename := cString(ev.Filename[:]) + switch ev.Kind { + case eventKindSnapshot: + exe, cmdline, enrErr := enrichFromProc(ev.Tgid) + if enrErr != nil { + reconciler.AccountEnrichmentMiss() + } + snapCount.Add(1) + reconciler.UpsertSnapshot(libebpf.ProcessRecord{ + Key: key, + Comm: comm, + Filename: filename, + ExePath: exe, + Cmdline: cmdline, + }) + case eventKindExec: + // Short-lived execs often exit before /proc enrichment; that is expected. + exe, cmdline, _ := enrichFromProc(ev.Tgid) + execCount.Add(1) + _ = reconciler.EnqueueHot(libebpf.HotEvent{ + Key: key, + Kind: ev.Kind, + Timestamp: ev.TimestampNs, + Comm: comm, + Filename: filename, + ExePath: exe, + Cmdline: cmdline, + }) + } + } + }() + + // Attach hot path before running the iterator so events during baseline land in the pending queue. + tp, err := link.Tracepoint("sched", "sched_process_exec", execObjs.HandleSchedProcessExec, nil) + if err != nil { + close(stop) + _ = rd.Close() + <-done + return nil, fmt.Errorf("attaching sched_process_exec: %w", err) + } + defer tp.Close() + + it, err := link.AttachIter(link.IterOptions{Program: iterObjs.DumpTask}) + if err != nil { + close(stop) + _ = rd.Close() + <-done + return nil, fmt.Errorf("attaching iter/task: %w", err) + } + defer it.Close() + + // Generate hot traffic while the iterator runs so pending-queue reconciliation is exercised. + trafficStop := make(chan struct{}) + trafficDone := make(chan struct{}) + go func() { + defer close(trafficDone) + for { + select { + case <-trafficStop: + return + default: + runTrueOnce() + time.Sleep(10 * time.Millisecond) + } + } + }() + + file, err := it.Open() + if err != nil { + close(trafficStop) + <-trafficDone + close(stop) + _ = rd.Close() + <-done + return nil, fmt.Errorf("opening task iterator: %w", err) + } + _, _ = io.Copy(io.Discard, file) + _ = file.Close() + + // Allow in-flight snapshot/hot records to drain, then finish baseline. + time.Sleep(500 * time.Millisecond) + close(trafficStop) + <-trafficDone + reconciler.FinishBaseline() + + // Generate a little exec traffic and observe live events. + deadline := time.Now().Add(duration) + for time.Now().Before(deadline) { + runTrueOnce() + time.Sleep(50 * time.Millisecond) + } + + var drop uint64 + var key uint32 + _ = execObjs.DropCount.Lookup(&key, &drop) + reconciler.AccountRingbufDrop(drop) + + close(stop) + _ = rd.Close() + <-done + + return &Result{ + Prerequisites: report, + Snapshots: int(snapCount.Load()), + ExecEvents: int(execCount.Load()), + Reconciled: reconciler.Size(), + Metrics: reconciler.Metrics.String(), + }, nil +} + +// FormatReport renders spike diagnostics for humans and CI logs. +func FormatReport(r *Result) string { + if r == nil { + return "" + } + if r.Prerequisites == nil { + return fmt.Sprintf("snapshots=%d exec_events=%d reconciled=%d\nmetrics: %s\n", + r.Snapshots, r.ExecEvents, r.Reconciled, r.Metrics) + } + return fmt.Sprintf( + "kernel=%s btf=%v ringbuf=%v iter=%v\nsnapshots=%d exec_events=%d reconciled=%d\nmetrics: %s\n", + r.Prerequisites.KernelRelease, + r.Prerequisites.BTFOK, + r.Prerequisites.RingbufOK, + r.Prerequisites.IterOK, + r.Snapshots, + r.ExecEvents, + r.Reconciled, + r.Metrics, + ) +} + +func parseSpikeEvent(raw []byte) (spikeEvent, error) { + var ev spikeEvent + if err := binary.Read(bytes.NewReader(raw), binary.LittleEndian, &ev); err != nil { + return ev, err + } + return ev, nil +} + +func cString(b []byte) string { + if i := bytes.IndexByte(b, 0); i >= 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() +} diff --git a/internal/ebpf/stats_integration_test.go b/internal/ebpf/stats_integration_test.go new file mode 100644 index 000000000..1ff99a911 --- /dev/null +++ b/internal/ebpf/stats_integration_test.go @@ -0,0 +1,94 @@ +//go:build linux && ebpf_integration + +/* + * 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 ebpf + +import ( + "encoding/json" + "os/exec" + "path/filepath" + "testing" + "time" + + "github.com/rabbitstack/fibratus/pkg/api" + "github.com/rabbitstack/fibratus/pkg/ps" + "github.com/rabbitstack/fibratus/pkg/util/rest" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// TestStatsSurfaceOverLiveCapture drives the same path fibratus stats takes: +// the API over its default UNIX socket, reading expvars produced by a live +// capture. Unit tests can assert the counters exist, but only this shows the +// command surface reporting numbers a running sensor actually moved. +func TestStatsSurfaceOverLiveCapture(t *testing.T) { + socket := filepath.Join(t.TempDir(), "fibratus.sock") + cfg := testConfig() + cfg.API.Transport = "unix://" + socket + cfg.API.Timeout = 5 * time.Second + + es := NewEventSource(ps.NewSnapshotter(), cfg, nil, nil).(*EventSource) + require.NoError(t, es.Open(cfg)) + t.Cleanup(func() { _ = es.Close() }) + + require.NoError(t, api.StartServer(cfg)) + t.Cleanup(func() { require.NoError(t, api.CloseServer()) }) + + // Drain, otherwise the queue fills and the counters stop advancing. + go func() { + for range es.Events() { + } + }() + + var vars map[string]any + deadline := time.Now().Add(20 * time.Second) + for time.Now().Before(deadline) { + _ = exec.Command("/bin/sh", "-c", "true").Run() + + body, err := rest.Get(rest.WithTransport(cfg.API.Transport), rest.WithURI("debug/vars")) + require.NoError(t, err) + require.NoError(t, json.Unmarshal(body, &vars)) + if processed, ok := vars["ebpf.events.processed"].(float64); ok && processed > 0 { + break + } + time.Sleep(200 * time.Millisecond) + } + + require.Contains(t, vars, "ebpf.events.processed") + assert.Greater(t, vars["ebpf.events.processed"], float64(0), "no events were captured") + + // Every counter the Linux stats table renders has to be present, or the + // command prints a zero for something that is simply not published. + for _, name := range []string{ + "ebpf.events.excluded", + "ebpf.events.unknown", + "ebpf.events.parse.errors", + "ebpf.ringbuf.drops", + "ebpf.approver.drops", + "ebpf.enrichment.miss", + "ebpf.startup.pending.queued", + "ebpf.startup.pending.dropped", + "ebpf.startup.replay.applied", + "ebpf.startup.snapshot.upserts", + "ebpf.startup.snapshot.late", + } { + assert.Contains(t, vars, name) + } +} diff --git a/internal/ebpf/testdata/execve.json b/internal/ebpf/testdata/execve.json new file mode 100644 index 000000000..f676d77b6 --- /dev/null +++ b/internal/ebpf/testdata/execve.json @@ -0,0 +1,19 @@ +{ + "name": "execve", + "pid": 4242, + "tid": 4242, + "seq": 7, + "params": { + "cmdline": "/bin/bash", + "exe": "/bin/bash", + "gid": "1000", + "name": "bash", + "pid": "4242", + "ppid": "1", + "retval": "0", + "start_boot_time": "123456789", + "syscall_id": "59", + "tid": "4242", + "uid": "1000" + } +} diff --git a/internal/etw/consumer.go b/internal/etw/consumer.go index 0044309c6..fc7131afb 100644 --- a/internal/etw/consumer.go +++ b/internal/etw/consumer.go @@ -135,7 +135,7 @@ func (c *Consumer) ProcessEvent(r *etw.EventRecord) error { // the filter is evaluated on the event to // decide whether it should get dropped if (evt.IsDropped(c.config.IsCaptureSet()) || - c.config.EventSource.ExcludeImage(evt.PS)) && !evt.IsStackWalk() { + c.config.EventSource.ExcludeProcess(evt.PS)) && !evt.IsStackWalk() { eventsExcluded.Add(1) return nil } diff --git a/internal/etw/source.go b/internal/etw/source.go index db0924c0a..edc919fe5 100644 --- a/internal/etw/source.go +++ b/internal/etw/source.go @@ -142,7 +142,7 @@ func (e *EventSource) Open(config *config.Config) error { continue } if typ == event.CreateProcess || typ == event.TerminateProcess || - typ == event.LoadModule || typ == event.UnloadModule { + typ == event.TerminateThread || typ == event.LoadModule || typ == event.UnloadModule { // always allow fundamental events continue } diff --git a/internal/etw/source_test.go b/internal/etw/source_test.go index 319b6230e..40a3c7a98 100644 --- a/internal/etw/source_test.go +++ b/internal/etw/source_test.go @@ -273,12 +273,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() @@ -1130,7 +1130,7 @@ func testCallstackEnrichment(t *testing.T, hsnap handle.Snapshotter, psnap ps.Sn BufferSize: 1024, MinBuffers: uint32(runtime.NumCPU() * 2), MaxBuffers: uint32((runtime.NumCPU() * 2) + 20), - ExcludedImages: []string{"System"}, + ExcludedProcesses: []string{"System"}, ExcludedEvents: []string{"WriteFile", "ReadFile", "RegOpenKey", "RegCloseKey", "CloseFile"}, FlushTimer: 1, } @@ -1138,10 +1138,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/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/make.bat b/make.bat index 4ee340d22..5d89dba6b 100644 --- a/make.bat +++ b/make.bat @@ -119,7 +119,7 @@ copy /y ".\cmd\fibratus\fibratus.ico" "%RELEASE_DIR%\Bin" copy /y ".\configs\fibratus.yml" "%RELEASE_DIR%\Config\fibratus.yml" robocopy ".\filaments" "%RELEASE_DIR%\Filaments" /E /S /XF *.md /XD __pycache__ .idea -robocopy ".\rules" "%RELEASE_DIR%\Rules" /E /S /XF *.md *.png +robocopy ".\rules" "%RELEASE_DIR%\Rules" /E /S /XF *.md *.png /XD linux :: Download the embedded Python distribution echo Downloading Python %PYTHON_VER%... @@ -177,7 +177,7 @@ copy /y ".\cmd\systray\fibratus-systray.exe" "%RELEASE_DIR%\Bin" copy /y ".\cmd\fibratus\fibratus.ico" "%RELEASE_DIR%\Bin" copy /y ".\configs\fibratus.yml" "%RELEASE_DIR%\Config\fibratus.yml" -robocopy ".\rules" "%RELEASE_DIR%\Rules" /E /S /XF *.md *.png +robocopy ".\rules" "%RELEASE_DIR%\Rules" /E /S /XF *.md *.png /XD linux :: Copy Debug Help DLL copy %SystemRoot%\System32\dbghelp.dll "%RELEASE_DIR%\Bin" diff --git a/pkg/aggregator/aggregator.go b/pkg/aggregator/aggregator.go index f1abfd045..d389119b4 100644 --- a/pkg/aggregator/aggregator.go +++ b/pkg/aggregator/aggregator.go @@ -37,10 +37,8 @@ import ( _ "github.com/rabbitstack/fibratus/pkg/outputs/null" // initialize alert senders - _ "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" // initialize transformers _ "github.com/rabbitstack/fibratus/pkg/aggregator/transformers/remove" diff --git a/pkg/aggregator/aggregator_windows.go b/pkg/aggregator/aggregator_windows.go new file mode 100644 index 000000000..9a379b1db --- /dev/null +++ b/pkg/aggregator/aggregator_windows.go @@ -0,0 +1,28 @@ +//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 aggregator + +import ( + // initialize Windows-only alert senders + _ "github.com/rabbitstack/fibratus/pkg/alertsender/eventlog" + _ "github.com/rabbitstack/fibratus/pkg/alertsender/systray" +) diff --git a/pkg/aggregator/transformers/config.go b/pkg/aggregator/transformers/config.go index b80270fc7..d0dae0094 100644 --- a/pkg/aggregator/transformers/config.go +++ b/pkg/aggregator/transformers/config.go @@ -18,13 +18,46 @@ package transformers -import "fmt" +import ( + "fmt" + + "github.com/rabbitstack/fibratus/pkg/util/mapdecoder" +) // ErrInvalidConfig signals an invalid transformer configuration var ErrInvalidConfig = func(name Type) error { return fmt.Errorf("invalid config for %q transformer", name) } +// ConfigLoader decodes raw config for a single transformer type. +// enabled reports whether the transformer's Enabled flag was set. +type ConfigLoader func(any) (Config, bool, error) + +// ConfigLoaders is the registry of configured transformers. +type ConfigLoaders map[Type]ConfigLoader + +func (loaders ConfigLoaders) Register(typ Type, loader ConfigLoader) { + if _, ok := loaders[typ]; ok { + panic(fmt.Sprintf("transformer loader %q is already registered", typ)) + } + loaders[typ] = loader +} + // Config acts as a container for the transformer configuration structures. type Config struct { Type Type - Transformer interface{} + Transformer any +} + +// LoadFromConfig builds a transformer loader for a config type T, decoding +// raw into it and reporting whether the transformer is enabled. +func LoadFromConfig[T any](typ Type, enabled func(T) bool) ConfigLoader { + return func(raw any) (Config, bool, error) { + var cfg T + if err := mapdecoder.Decode(raw, &cfg); err != nil { + return Config{}, false, err + } + if !enabled(cfg) { + return Config{}, false, nil + } + return Config{Type: typ, Transformer: cfg}, true, nil + } } diff --git a/pkg/aggregator/transformers/transformer.go b/pkg/aggregator/transformers/transformer.go index e08841637..d89a93e05 100644 --- a/pkg/aggregator/transformers/transformer.go +++ b/pkg/aggregator/transformers/transformer.go @@ -20,6 +20,7 @@ package transformers import ( "fmt" + "github.com/rabbitstack/fibratus/pkg/event" ) @@ -42,6 +43,7 @@ const ( Trim // Tags represents the tags transformer type. This transformer appends tags to the event's metadata. Tags + None ) // String returns the type human-readable name. @@ -62,6 +64,24 @@ func (typ Type) String() string { } } +// TypeFromString converts the string representation of the transformer to its corresponding type. +func TypeFromString(s string) Type { + switch s { + case "remove": + return Remove + case "rename": + return Rename + case "replace": + return Replace + case "trim": + return Trim + case "tags": + return Tags + default: + return None + } +} + // Register registers a singleton instance of the provided transformer. func Register(typ Type, factory Factory) { if _, ok := transformers[typ]; ok { diff --git a/pkg/alertsender/alert.go b/pkg/alertsender/alert.go index 4c0e64f9a..8fb024fff 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 uint32 `json:"pid"` - TID uint32 `json:"tid"` - PPID uint32 `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 uint32 `json:"pid"` - TID uint32 `json:"tid"` - PPID uint32 `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 uint32 `json:"pid"` - TID uint32 `json:"tid"` - PPID uint32 `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: e.Category().String(), 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("%s %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"` - 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_linux.go b/pkg/alertsender/alert_linux.go new file mode 100644 index 000000000..1c07fe3ba --- /dev/null +++ b/pkg/alertsender/alert_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 uint32 `json:"pid"` + TID uint32 `json:"tid"` + PPID uint32 `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_test.go b/pkg/alertsender/alert_test.go index 4425badfa..e66e2ff5e 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/alert_windows.go b/pkg/alertsender/alert_windows.go new file mode 100644 index 000000000..b2cb17b47 --- /dev/null +++ b/pkg/alertsender/alert_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 uint32 `json:"pid"` + TID uint32 `json:"tid"` + PPID uint32 `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/alertsender/config.go b/pkg/alertsender/config.go index 5052c4f6e..5b89e2c9a 100644 --- a/pkg/alertsender/config.go +++ b/pkg/alertsender/config.go @@ -18,8 +18,43 @@ package alertsender +import ( + "fmt" + + "github.com/rabbitstack/fibratus/pkg/util/mapdecoder" +) + +// ConfigLoader defines the alert sender configuration loader. +type ConfigLoader func(any) (Config, bool, error) + // Config is the container for the alert sender configuration structure. type Config struct { Type Type - Sender interface{} + Sender any +} + +// ConfigLoaders is the registry of configured alert senders. +type ConfigLoaders map[Type]ConfigLoader + +// Register registers a new alert sender config loader. +func (loaders ConfigLoaders) Register(typ Type, loader ConfigLoader) { + if _, ok := loaders[typ]; ok { + panic(fmt.Sprintf("alertsender loader %q is already registered", typ)) + } + loaders[typ] = loader +} + +// LoadFromConfig builds a sender loader for a config type T, decoding +// raw into it and skipping it when the enabled predicate reports false. +func LoadFromConfig[T any](typ Type, enabled func(T) bool) ConfigLoader { + return func(raw any) (Config, bool, error) { + var cfg T + if err := mapdecoder.Decode(raw, &cfg); err != nil { + return Config{}, false, err + } + if !enabled(cfg) { + return Config{}, false, nil + } + return Config{Type: typ, Sender: cfg}, true, nil + } } 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 6d855ea25..b3f71b9e3 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 7b765d7f2..fe48e0875 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/mail/renderer_test.go b/pkg/alertsender/mail/renderer_test.go index e5438d3a9..861d58153 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/alertsender/sender.go b/pkg/alertsender/sender.go index 80fa70946..6ecba0464 100644 --- a/pkg/alertsender/sender.go +++ b/pkg/alertsender/sender.go @@ -20,6 +20,7 @@ package alertsender import ( "fmt" + "github.com/rabbitstack/fibratus/pkg/util/multierror" ) @@ -93,6 +94,8 @@ func ToType(s string) Type { return Noop case "systray": return Systray + case "eventlog": + return Eventlog default: return None } 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/api/dialer_linux.go b/pkg/api/dialer_linux.go new file mode 100644 index 000000000..ade0ad059 --- /dev/null +++ b/pkg/api/dialer_linux.go @@ -0,0 +1,33 @@ +/* + * Copyright 2019-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 api + +import ( + "context" + "net" + "strings" +) + +// 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/dialer_windows.go b/pkg/api/dialer_windows.go new file mode 100644 index 000000000..72b6b7e27 --- /dev/null +++ b/pkg/api/dialer_windows.go @@ -0,0 +1,34 @@ +/* + * Copyright 2019-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 api + +import ( + "context" + "net" + + "github.com/Microsoft/go-winio" +) + +// DialLocalTransport creates a dialer to be used with the http.Client to connect to a named pipe. +func DialLocalTransport(path string) func(context.Context, string, string) (net.Conn, error) { + npipe := transformPipePath(path) + return func(ctx context.Context, _, _ string) (net.Conn, error) { + return winio.DialPipeContext(ctx, npipe) + } +} diff --git a/pkg/api/listener.go b/pkg/api/listener.go index 433a9b9a6..7f3de1463 100644 --- a/pkg/api/listener.go +++ b/pkg/api/listener.go @@ -1,6 +1,3 @@ -//go:build windows -// +build windows - /* * Copyright 2019-2020 by Nedim Sabic Sabic * https://www.fibratus.io @@ -22,49 +19,11 @@ package api import ( - "context" - "fmt" "net" - "strings" - - "github.com/Microsoft/go-winio" ) -// MakePipeListener produces a new listener for receiving requests over a named pipe. -func MakePipeListener(pipePath, descriptor string) (net.Listener, error) { - npipe := transformPipePath(pipePath) - l, err := winio.ListenPipe(npipe, &winio.PipeConfig{SecurityDescriptor: descriptor}) - if err != nil { - return nil, fmt.Errorf("fail to listen on the %q pipe: %v", pipePath, err) - } - return l, nil -} - -// makeTCPListener produces a new listener for receiving requests over TCP. -func makeTCPListener(addr string) (net.Listener, error) { +// MakeTCPListener produces a new listener for receiving requests over TCP. +func MakeTCPListener(addr string) (net.Listener, error) { //nolint:noctx 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) { - npipe := transformPipePath(pipePath) - return func(ctx context.Context, _, _ string) (net.Conn, error) { - return winio.DialPipeContext(ctx, npipe) - } -} - -// transformPipePath takes an input type name defined as a URI like `npipe:///hello` and transform it into -// `\\.\pipe\hello`. Borrowed from https://github.com/elastic/beats/blob/master/libbeat/api/npipe/listener_windows.go -func transformPipePath(name string) string { - if strings.HasPrefix(name, "npipe:///") { - path := strings.TrimPrefix(name, "npipe:///") - return `\\.\pipe\` + path - } - - if strings.HasPrefix(name, `\\.\pipe\`) { - return name - } - - return name -} diff --git a/pkg/api/listener_linux.go b/pkg/api/listener_linux.go new file mode 100644 index 000000000..3bd8abe5a --- /dev/null +++ b/pkg/api/listener_linux.go @@ -0,0 +1,60 @@ +//go:build linux + +/* + * Copyright 2026 by Mostafa Moradian + * 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 api + +import ( + "fmt" + "net" + "os" + "strings" +) + +// MakeListener builds a new listener that either accepts traffic over UNIX domain socket or TCP. +func MakeListener(transport string) (net.Listener, error) { + if strings.HasPrefix(transport, "unix://") { + path := strings.TrimPrefix(transport, "unix://") + return makeUNIXSocketListener(path) + } + return MakeTCPListener(transport) +} + +// makeUNIXSocketListener produces a new listener for receiving requests over a UNIX domain socket. +func makeUNIXSocketListener(path string) (net.Listener, error) { + // remove any stale socket file left behind by a previous run. + if err := os.Remove(path); err != nil && !os.IsNotExist(err) { + return nil, fmt.Errorf("failed to remove stale socket %q: %v", path, err) + } + + l, err := net.Listen("unix", path) + if err != nil { + return nil, fmt.Errorf("fail to listen on the %q socket: %v", path, err) + } + + // restrict the socket to the owning user only, mirroring the + // single-user access granted to the named pipe on Windows. + if err := os.Chmod(path, 0600); err != nil { + l.Close() + return nil, fmt.Errorf("failed to set permissions on the %q socket: %v", path, err) + } + + return l, nil +} 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/api/listener_windows.go b/pkg/api/listener_windows.go new file mode 100644 index 000000000..65e584590 --- /dev/null +++ b/pkg/api/listener_windows.go @@ -0,0 +1,73 @@ +//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 api + +import ( + "fmt" + "net" + "os/user" + "strings" + + "github.com/Microsoft/go-winio" +) + +// MakeListener builds a new listener that either accepts traffic over named pipe or TCP socket. +func MakeListener(transport string) (net.Listener, error) { + if strings.HasPrefix(transport, `npipe:///`) { + usr, err := user.Current() + if err != nil { + return nil, fmt.Errorf("failed to retrieve the current user: %v", err) + } + // Named pipe security and access rights. + // We create the pipe and the specific users should only be able to write to it. + // See docs: https://docs.microsoft.com/en-us/windows/win32/ipc/named-pipe-security-and-access-rights + // String definition: https://docs.microsoft.com/en-us/windows/win32/secauthz/ace-strings + // Give generic read/write access to the specified user. + descriptor := "D:P(A;;GA;;;" + usr.Uid + ")" + return makePipeListener(transport, descriptor) + } + return MakeTCPListener(transport) +} + +// makePipeListener produces a new listener for receiving requests over a named pipe. +func makePipeListener(pipePath, descriptor string) (net.Listener, error) { + npipe := transformPipePath(pipePath) + l, err := winio.ListenPipe(npipe, &winio.PipeConfig{SecurityDescriptor: descriptor}) + if err != nil { + return nil, fmt.Errorf("fail to listen on the %q pipe: %v", pipePath, err) + } + return l, nil +} + +// transformPipePath takes an input type name defined as a URI like `npipe:///hello` and transform it into +// `\\.\pipe\hello`. Borrowed from https://github.com/elastic/beats/blob/master/libbeat/api/npipe/listener_windows.go +func transformPipePath(name string) string { + if strings.HasPrefix(name, "npipe:///") { + path := strings.TrimPrefix(name, "npipe:///") + return `\\.\pipe\` + path + } + + if strings.HasPrefix(name, `\\.\pipe\`) { + return name + } + + return name +} diff --git a/pkg/api/server.go b/pkg/api/server.go index 2d1848c8b..c0412a757 100644 --- a/pkg/api/server.go +++ b/pkg/api/server.go @@ -1,5 +1,5 @@ /* - * Copyright 2020-2021 by Nedim Sabic Sabic + * Copyright 2020-2026 by Nedim Sabic Sabic * https://www.fibratus.io * All Rights Reserved. * @@ -19,34 +19,54 @@ package api import ( + "context" + "errors" "expvar" - "github.com/rabbitstack/fibratus/pkg/api/handler" - "github.com/rabbitstack/fibratus/pkg/config" - log "github.com/sirupsen/logrus" "net" "net/http" "net/http/pprof" "runtime/debug" "strings" + + "github.com/rabbitstack/fibratus/pkg/api/handler" + "github.com/rabbitstack/fibratus/pkg/config" + log "github.com/sirupsen/logrus" ) -func setupServer(lis net.Listener, c *config.Config) { +// Server wraps http.Server and owns the router lifecycle. +type Server struct { + http *http.Server + lis net.Listener +} + +// NewServer builds a Server bound to the given listener, wired +// with the config, debug/vars and pprof endpoints. +func NewServer(c *config.Config) (*Server, error) { mux := http.NewServeMux() mux.Handle("/config", handler.Config(c)) mux.Handle("/debug/vars", expvar.Handler()) mux.HandleFunc("/debug/pprof/", pprof.Index) mux.HandleFunc("/debug/pprof/profile", pprof.Profile) - mux.HandleFunc("/debug/freemem", func(writer http.ResponseWriter, request *http.Request) { + mux.HandleFunc("/debug/freemem", func(w http.ResponseWriter, r *http.Request) { debug.FreeOSMemory() }) - srv := &http.Server{ - Handler: mux, + lis, err := MakeListener(c.API.Transport) + if err != nil { + return nil, err } + return &Server{ + lis: lis, + http: &http.Server{Handler: mux}, + }, nil +} + +// Start begins serving in the background. It does not block. +func (s *Server) Start() { go func() { - if err := srv.Serve(lis); err != nil && err != http.ErrServerClosed { + if err := s.http.Serve(s.lis); err != nil && !errors.Is(err, http.ErrServerClosed) { if strings.Contains(err.Error(), "use of closed network connection") { return } @@ -54,3 +74,8 @@ func setupServer(lis net.Listener, c *config.Config) { } }() } + +// Stop gracefully shuts down the server. +func (s *Server) Stop(ctx context.Context) error { + return s.http.Shutdown(ctx) +} diff --git a/pkg/api/server_linux_test.go b/pkg/api/server_linux_test.go new file mode 100644 index 000000000..2295bc58d --- /dev/null +++ b/pkg/api/server_linux_test.go @@ -0,0 +1,108 @@ +//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_test lives outside the package because the REST client imports +// the API for its local transport dialer. +package api_test + +import ( + "context" + "encoding/json" + "net" + "os" + "path/filepath" + "testing" + + "github.com/rabbitstack/fibratus/pkg/api" + "github.com/rabbitstack/fibratus/pkg/config" + "github.com/rabbitstack/fibratus/pkg/util/rest" + "github.com/spf13/cobra" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// The config endpoint renders through viper, so the config has to come from +// the normal construction path rather than a bare struct. +func newConfig(t *testing.T, transport string) *config.Config { + t.Helper() + c := config.NewWithOpts(config.WithRun()) + c.MustViperize(&cobra.Command{}) + require.NoError(t, c.Init()) + c.API.Transport = transport + return c +} + +func freeTCPAddr(t *testing.T) string { + t.Helper() + l, err := net.Listen("tcp", "127.0.0.1:0") + require.NoError(t, err) + addr := l.Addr().String() + require.NoError(t, l.Close()) + return addr +} + +// The endpoints behind fibratus config and fibratus stats have to answer over +// both transports, since a socket is the default and a TCP address is what an +// operator switches to for remote access. +func TestServerServesBothTransports(t *testing.T) { + for _, transport := range []string{ + "unix://" + filepath.Join(t.TempDir(), "fibratus.sock"), + freeTCPAddr(t), + } { + t.Run(transport, func(t *testing.T) { + cfg := newConfig(t, transport) + srv, err := api.NewServer(cfg) + require.NoError(t, err) + srv.Start() + t.Cleanup(func() { require.NoError(t, srv.Stop(context.Background())) }) + + body, err := rest.Get(rest.WithTransport(transport), rest.WithURI("debug/vars")) + require.NoError(t, err) + var vars map[string]any + require.NoError(t, json.Unmarshal(body, &vars)) + assert.Contains(t, vars, "cmdline", "expvar payload is what fibratus stats reads") + + // This endpoint renders the config as text, which is what + // fibratus config prints verbatim. + body, err = rest.Get(rest.WithTransport(transport), rest.WithURI("config")) + require.NoError(t, err) + for _, section := range []string{"aggregator", "api", "eventsource", "filters", "output"} { + assert.Contains(t, string(body), section) + } + }) + } +} + +// A socket left behind by a killed process must not keep the server from +// starting, otherwise an unclean shutdown needs manual cleanup before restart. +func TestServerReplacesStaleSocket(t *testing.T) { + socket := filepath.Join(t.TempDir(), "fibratus.sock") + require.NoError(t, os.WriteFile(socket, nil, 0o600)) + + cfg := newConfig(t, "unix://"+socket) + srv, err := api.NewServer(cfg) + require.NoError(t, err) + srv.Start() + t.Cleanup(func() { require.NoError(t, srv.Stop(context.Background())) }) + + body, err := rest.Get(rest.WithTransport("unix://"+socket), rest.WithURI("debug/vars")) + require.NoError(t, err) + assert.NotEmpty(t, body) +} diff --git a/pkg/api/server_windows.go b/pkg/api/server_windows.go deleted file mode 100644 index 2884a0a2b..000000000 --- a/pkg/api/server_windows.go +++ /dev/null @@ -1,68 +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 api - -import ( - "fmt" - "github.com/rabbitstack/fibratus/pkg/config" - "net" - "os/user" - "strings" -) - -var listener net.Listener - -// StartServer starts the HTTP server with the specified configuration. -func StartServer(c *config.Config) error { - var err error - apiConfig := c.API - if strings.HasPrefix(apiConfig.Transport, `npipe:///`) { - usr, err := user.Current() - if err != nil { - return fmt.Errorf("failed to retrieve the current user: %v", err) - } - // Named pipe security and access rights. - // We create the pipe and the specific users should only be able to write to it. - // See docs: https://docs.microsoft.com/en-us/windows/win32/ipc/named-pipe-security-and-access-rights - // String definition: https://docs.microsoft.com/en-us/windows/win32/secauthz/ace-strings - // Give generic read/write access to the specified user. - descriptor := "D:P(A;;GA;;;" + usr.Uid + ")" - listener, err = MakePipeListener(apiConfig.Transport, descriptor) - if err != nil { - return err - } - } else { - listener, err = makeTCPListener(apiConfig.Transport) - } - if err != nil { - return err - } - - setupServer(listener, c) - - return nil -} - -// CloseServer shutdowns the server by stopping the listener. -func CloseServer() error { - if listener != nil { - return listener.Close() - } - return nil -} diff --git a/pkg/callstack/callstack_linux.go b/pkg/callstack/callstack_linux.go new file mode 100644 index 000000000..b3530e7d3 --- /dev/null +++ b/pkg/callstack/callstack_linux.go @@ -0,0 +1,58 @@ +//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 callstack + +// Callstack is a sequence of stack frames. +type Callstack []Frame + +// Frame describes a single stack frame. +type Frame struct { + 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 { + return "" +} + +// Colorize returns a plain string representation on Linux. +func (s Callstack) Colorize() string { return s.String() } 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/callstack/callstack.go b/pkg/callstack/callstack_windows.go similarity index 99% rename from pkg/callstack/callstack.go rename to pkg/callstack/callstack_windows.go index 21f2298c1..2a0e9e63b 100644 --- a/pkg/callstack/callstack.go +++ b/pkg/callstack/callstack_windows.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2021-present by Nedim Sabic Sabic * https://www.fibratus.io 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..16b420d22 --- /dev/null +++ b/pkg/cap/version/version_linux.go @@ -0,0 +1,36 @@ +//go:build linux + +/* + * 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 version + +type Version uint16 + +const ( + EvtSecV1 Version = iota + 1 + EvtSecV2 +) + +const ( + ProcessSecV1 Version = iota + 1 + ProcessSecV2 + ProcessSecV3 + ProcessSecV4 +) diff --git a/pkg/config/alertsender.go b/pkg/config/alertsender.go index 06f033088..a600a2c15 100644 --- a/pkg/config/alertsender.go +++ b/pkg/config/alertsender.go @@ -1,5 +1,6 @@ /* * Copyright 2019-2020 by Nedim Sabic Sabic + * Copyright 2026 by Mostafa Moradian * https://www.fibratus.io * All Rights Reserved. * @@ -21,95 +22,58 @@ 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") +var ErrNoAlertsendersSection = errors.New("no alertsenders section in config") -var errAlertsenderConfig = func(sender string, err error) error { +var ErrAlertsenderConfig = func(sender string, err error) error { return fmt.Errorf("%s alert sender invalid config: %v", sender, err) } -func (c *Config) tryLoadAlertSenders() error { +var senders = alertsender.ConfigLoaders{} + +func init() { + senders.Register(alertsender.Mail, alertsender.LoadFromConfig(alertsender.Mail, func(c mail.Config) bool { return c.Enabled })) + senders.Register(alertsender.Slack, alertsender.LoadFromConfig(alertsender.Slack, func(c slack.Config) bool { return c.Enabled })) +} + +// TryLoadAlertSenders loads configs for all registered alert senders. +func (c *BaseConfig) TryLoadAlertSenders() error { if c.ForwardMode || c.IsCaptureSet() { // In event forwarding mode or capture control, alert senders are useless return nil } - configs := make([]alertsender.Config, 0) alertsenders := c.viper.AllSettings()["alertsenders"] if alertsenders == nil { - return errNoAlertsendersSection + return ErrNoAlertsendersSection } - mapping, ok := alertsenders.(map[string]interface{}) + mapping, ok := alertsenders.(map[string]any) if !ok { return fmt.Errorf("expected map[string]interface{} type for alertsenders but found %s", reflect.TypeOf(alertsenders)) } - for typ, config := range mapping { - switch typ { - case "mail": - var mailConfig mail.Config - if err := decode(config, &mailConfig); err != nil { - return errAlertsenderConfig(typ, err) - } - if !mailConfig.Enabled { - continue - } - config := alertsender.Config{ - Type: alertsender.Mail, - Sender: mailConfig, - } - configs = append(configs, config) - case "slack": - var slackConfig slack.Config - if err := decode(config, &slackConfig); err != nil { - return errAlertsenderConfig(typ, err) - } - if !slackConfig.Enabled { - continue - } - config := alertsender.Config{ - Type: alertsender.Slack, - Sender: slackConfig, - } - 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) + configs := make([]alertsender.Config, 0, len(mapping)) + for name, raw := range mapping { + loader, ok := senders[alertsender.ToType(name)] + if !ok { + return fmt.Errorf("unknown alertsender type %q", name) + } + cfg, enabled, err := loader(raw) + if err != nil { + return ErrAlertsenderConfig(name, err) } + if !enabled { + continue + } + configs = append(configs, cfg) } - c.Alertsenders = configs return nil diff --git a/pkg/config/alertsender_linux_test.go b/pkg/config/alertsender_linux_test.go new file mode 100644 index 000000000..174d56d9d --- /dev/null +++ b/pkg/config/alertsender_linux_test.go @@ -0,0 +1,57 @@ +/* + * 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 TestAlertSenders(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/alertsender_windows.go b/pkg/config/alertsender_windows.go new file mode 100644 index 000000000..70e1bc0a0 --- /dev/null +++ b/pkg/config/alertsender_windows.go @@ -0,0 +1,33 @@ +//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 init() { + senders.Register(alertsender.Eventlog, alertsender.LoadFromConfig(alertsender.Eventlog, func(c eventlog.Config) bool { return c.Enabled })) + senders.Register(alertsender.Systray, alertsender.LoadFromConfig(alertsender.Systray, func(c systray.Config) bool { return c.Enabled })) +} diff --git a/pkg/config/alertsender_windows_test.go b/pkg/config/alertsender_windows_test.go new file mode 100644 index 000000000..993fbfecf --- /dev/null +++ b/pkg/config/alertsender_windows_test.go @@ -0,0 +1,63 @@ +/* + * 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/eventlog" + "github.com/rabbitstack/fibratus/pkg/alertsender/mail" + "github.com/rabbitstack/fibratus/pkg/alertsender/slack" + "github.com/rabbitstack/fibratus/pkg/alertsender/systray" + "github.com/stretchr/testify/require" +) + +func TestAlertSenders(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, 4) + 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) + case alertsender.Systray: + require.IsType(t, systray.Config{}, sender.Sender) + case alertsender.Eventlog: + require.IsType(t, eventlog.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..4f56a1b0c --- /dev/null +++ b/pkg/config/config.go @@ -0,0 +1,307 @@ +/* + * 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" +) + +// BaseConfig stores configuration options that are platform-neutral. +type BaseConfig struct { + // 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 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 + 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) + +// 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 base configuration store from files, environment variables, and flags. +func newWithOpts(options ...Option) BaseConfig { + opts := &Options{} + for _, option := range options { + option(opts) + } + + v := viper.New() + v.AutomaticEnv() + v.SetEnvKeyReplacer(strings.NewReplacer("-", "_", ".", "_")) + + c := BaseConfig{ + 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() + + return c +} + +// MustViperize adds the configuration flags to the Cobra command. +func (c *BaseConfig) 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 and +// loads/decodes output, transformer and alert sender configs. +func (c *BaseConfig) init() error { + c.initFromViper() + + if !c.opts.run && !c.opts.replay { + return nil + } + + 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 *BaseConfig) initFromViper() { + 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) +} + +// GetConfigFile gets the path of the configuration file from Viper value. +func (c *BaseConfig) GetConfigFile() string { return c.viper.GetString(configFile) } + +// GetFilters returns all rule filters loaded into the engine. +func (c *BaseConfig) GetFilters() []*FilterConfig { + if c.Filters == nil { + return nil + } + return c.Filters.filters +} + +// TryLoadFile attempts to load the configuration file from specified path on the file system. +func (c *BaseConfig) TryLoadFile(file string) error { + c.viper.SetConfigFile(file) + return c.viper.ReadInConfig() +} + +// 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 *BaseConfig) Validate() error { + // we'll first validate the structure and values of the config file + file := c.viper.GetString(configFile) + var out any + 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) + } + + // validate config file content + valid, errs := validate(configSchema, out) + if !valid || len(errs) > 0 { + return fmt.Errorf("invalid config: %v", multierror.Wrap(errs...)) + } + + // 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 +} + +func (c *BaseConfig) IsCaptureSet() bool { return c.CapFile != "" } +func (c *BaseConfig) IsFilamentSet() bool { return c.Filament.Name != "" } +func (c *BaseConfig) ConfigExists() bool { _, err := os.Stat(c.File()); return err == nil } +func (c *BaseConfig) File() string { return c.viper.GetString(configFile) } + +func (c *BaseConfig) addFlags() { + c.flags.String(configFile, configFilePath, "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, rulesPaths, "Comma-separated list of rules files") + c.flags.StringSlice(macrosFromPaths, macrosPaths, "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, filamentsPaths, "Denotes the directory where filaments are located") + } + if c.opts.run || c.opts.replay || c.opts.capture || c.opts.stats { + c.flags.String(transport, apiTransport, "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) + c.EventSource.AddFlags(c.flags) +} diff --git a/pkg/config/config_linux.go b/pkg/config/config_linux.go new file mode 100644 index 000000000..20eb0c41d --- /dev/null +++ b/pkg/config/config_linux.go @@ -0,0 +1,62 @@ +//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 ( + "path/filepath" +) + +var ( + // configFilePath defines the default value for the configuration file path + configFilePath = filepath.Join("/etc", "fibratus", "fibratus.yml") + + // filamentsPaths defines the default directory containing filament scripts + filamentsPaths = filepath.Join("/usr", "share", "fibratus", "filaments") + + // rulesPaths defines default rule paths + rulesPaths = []string{filepath.Join("/etc", "fibratus", "rules", "*")} + + // macrosPaths defines default macro paths + macrosPaths = []string{filepath.Join("/etc", "fibratus", "rules", "macros", "*")} + + // apiTransport apiTransport defines the default transport protocol for + // the API server. It keeps the API off the network unless someone asks + // for it. Filesystem permissions on the socket then decide who can reach it. + apiTransport = "unix:///var/run/fibratus.sock" +) + +// Config exposes the platform configuration options. +type Config struct { + BaseConfig +} + +// NewWithOpts builds a new platform configuration store. +func NewWithOpts(options ...Option) *Config { + c := &Config{ + BaseConfig: newWithOpts(options...), + } + return c +} + +// Init initializes the config state. +func (c *Config) Init() error { + return c.BaseConfig.init() +} diff --git a/pkg/config/config_linux_test.go b/pkg/config/config_linux_test.go new file mode 100644 index 000000000..c1922d507 --- /dev/null +++ b/pkg/config/config_linux_test.go @@ -0,0 +1,46 @@ +//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 ( + "path/filepath" + "testing" + + "github.com/spf13/cobra" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestDefaults(t *testing.T) { + // No config file on the box, which is the state a fresh install starts in. + c := NewWithOpts(WithRun()) + cmd := &cobra.Command{} + c.MustViperize(cmd) + require.NoError(t, c.Init()) + + // The API stays off the network unless asked, so a default install exposes + // nothing beyond what socket permissions allow. + assert.Equal(t, "unix:///var/run/fibratus.sock", c.API.Transport) + + assert.Equal(t, filepath.Join("/etc", "fibratus", "fibratus.yml"), configFilePath) + assert.Equal(t, []string{filepath.Join("/etc", "fibratus", "rules", "*")}, rulesPaths) + assert.Equal(t, []string{filepath.Join("/etc", "fibratus", "rules", "macros", "*")}, macrosPaths) +} diff --git a/pkg/config/config_windows.go b/pkg/config/config_windows.go index 34670fd4e..8a983cb85 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,227 +21,88 @@ package config import ( - "encoding/json" - "fmt" - "time" - "github.com/rabbitstack/fibratus/internal/evasion" "golang.org/x/sys/windows" - "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/pkg/alertsender/eventlog" + "github.com/rabbitstack/fibratus/pkg/alertsender/systray" "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" ) 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" + serializeEnvs = "event.serialize-envs" serializeHandles = "event.serialize-handles" serializePE = "event.serialize-pe" - serializeEnvs = "event.serialize-envs" ) -// Config stores configuration options for fine-tuning the behaviour of Fibratus. +var ( + // configFilePath defines the default value for the configuration file path + configFilePath = filepath.Join(os.Getenv("PROGRAMFILES"), "fibratus", "config", "fibratus.yml") + + // filamentsPaths defines the default directory containing filament scripts + filamentsPaths = filepath.Join(os.Getenv("PROGRAMFILES"), "fibratus", "filaments") + + // rulesPaths defines default rule paths + rulesPaths = []string{filepath.Join(rulesDir(), "*")} + + // macrosPaths defines default macro paths + macrosPaths = []string{filepath.Join(rulesDir(), "Macros", "*")} + + // apiTransport defines the default transport protocol for the API server + apiTransport = "http://localhost:8482" +) + +// Config exposes the platform configuration options. 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"` + BaseConfig // 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 -} - -// 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 - } -} - -// NewWithOpts builds a new configuration store from a variety of sources such as configuration files, -// environment variables or command line flags. +// NewWithOpts builds a new platform configuration store. 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) - 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) + BaseConfig: newWithOpts(options...), + PE: pe.Config{}, + Yara: yara.Config{}, } c.addFlags() @@ -247,197 +110,67 @@ func NewWithOpts(options ...Option) *Config { return c } -// GetConfigFile gets the path of the configuration file from Viper value. -func (c Config) GetConfigFile() string { - return c.viper.GetString(configFile) +// Init initializes the config state. +func (c *Config) Init() error { + c.initFromViper() + return c.init() } -// GetFilters returns all rule filters loaded into the engine. -func (c Config) GetFilters() []*FilterConfig { - if c.Filters == nil { - return nil +// addFlags populates the platform flags set. +func (c *Config) addFlags() { + if c.opts.run || c.opts.replay { + systray.AddFlags(c.flags) + eventlog.AddFlags(c.flags) + yara.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 || c.opts.capture { + pe.AddFlags(c.flags) } - if c.opts.capture || c.opts.replay { - if err := cmd.MarkPersistentFlagRequired(capFile); err != nil { - panic(err) - } + if c.opts.run { + evasion.AddFlags(c.flags) + } + 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) initFromViper() { 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) } - - return nil } -// IsCaptureSet determines if the events are stored -// in the capture file. -func (c *Config) IsCaptureSet() bool { return c.CapFile != "" } - -// IsFilamentSet indicates if the filament is supplied. -func (c *Config) IsFilamentSet() bool { return c.Filament.Name != "" } - -// 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() -} - -// 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 rulesDir() 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...)) - } - // 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...)) + exe = filepath.Join(os.Getenv("ProgramFiles"), "Fibratus", "Bin", "fibratus.exe") } - 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(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(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 2d691a316..1fe873c2e 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,129 +20,45 @@ package config import ( - "runtime" - "time" - "github.com/rabbitstack/fibratus/pkg/event" - "github.com/rabbitstack/fibratus/pkg/util/bitmap" - pstypes "github.com/rabbitstack/fibratus/pkg/ps/types" - "github.com/spf13/viper" + "github.com/rabbitstack/fibratus/pkg/util/bitmap" ) -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" - enableMemEvents = "eventsource.enable-mem" - enableAuditAPIEvents = "eventsource.enable-audit-api" - enableDNSEvents = "eventsource.enable-dns" - 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" +const excludedEvents = "eventsource.blacklist.events" +const excludedProcesses = "eventsource.blacklist.images" - maxBufferSize = uint32(512) -) +// EventFilter defines the dropped event types bitmap and the processes exclusion map. +type EventFilter struct { + // Types is the bitmap with dropped event masks. + Types bitmap.Bitmap[event.Type] -var ( - defaultMinBuffers = uint32(runtime.NumCPU() * 2) - defaultMaxBuffers = uint32(runtime.NumCPU() * 8) - defaultFlushInterval = time.Second -) + // Processes contains the list of process executables names + // that are dropped in the event processing pipeline. + Processes map[string]bool +} -// 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"` - // 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"` - // 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"` +// BaseEventSourceConfig contains platform-neutral event source configuration. +type BaseEventSourceConfig struct { + EventFilter // 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"` - - dropBitmap bitmap.Bitmap[event.Type] - - excludedImages map[string]bool + // ExcludedProcesses are process image names that will be rejected if they generate a kernel event. + ExcludedProcesses []string `json:"blacklist.images" yaml:"blacklist.images"` } -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.EnableMemEvents = v.GetBool(enableMemEvents) - c.EnableAuditAPIEvents = v.GetBool(enableAuditAPIEvents) - c.EnableDNSEvents = v.GetBool(enableDNSEvents) - 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.excludedImages = make(map[string]bool) +// Init initializes event and process exclusion rules. +func (c *BaseEventSourceConfig) Init() { + c.Processes = make(map[string]bool) for _, name := range c.ExcludedEvents { if typ, ok := event.ParseType(name); ok { - c.dropBitmap.Set(typ) + c.Types.Set(typ) } } - for _, name := range c.ExcludedImages { - c.excludedImages[name] = true - } -} - -// Init is an exported method to allow initializing exclusion maps from external modules. -func (c *EventSourceConfig) Init() { - c.excludedImages = make(map[string]bool) - - for _, name := range c.ExcludedEvents { - if typ, ok := event.ParseType(name); ok { - c.dropBitmap.Set(typ) - } - } - - for _, name := range c.ExcludedImages { - c.excludedImages[name] = true + for _, name := range c.ExcludedProcesses { + c.Processes[name] = true } } @@ -152,30 +66,23 @@ func (c *EventSourceConfig) Init() { // instruct the given event type should be dropped from // the event stream. func (c *EventSourceConfig) SetDropMask(typ event.Type) { - c.dropBitmap.Set(typ) + c.Types.Set(typ) } // TestDropMask checks if the specified event type has // the drop mask in the bitset. func (c *EventSourceConfig) TestDropMask(typ event.Type) bool { - return c.dropBitmap.Has(typ) + return c.Types.Has(typ) } // ExcludeEvent determines whether the event type is declared // in the exclusion list. func (c *EventSourceConfig) ExcludeEvent(typ event.Type) bool { - return c.dropBitmap.Has(typ) + return c.Types.Has(typ) } -// 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] +// ExcludeProcess determines whether the event is excluded by the +// originating process name. +func (c *EventSourceConfig) ExcludeProcess(ps *pstypes.PS) bool { + return ps != nil && c.Processes[ps.Name] } diff --git a/pkg/config/eventsource_linux.go b/pkg/config/eventsource_linux.go new file mode 100644 index 000000000..3eb6adbdc --- /dev/null +++ b/pkg/config/eventsource_linux.go @@ -0,0 +1,58 @@ +//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/spf13/pflag" + "github.com/spf13/viper" +) + +const ( + enableFileIOEvents = "eventsource.enable-fileio" + enableNetEvents = "eventsource.enable-net" + enableMemEvents = "eventsource.enable-mem" +) + +// EventSourceConfig stores different configuration options for fine-tuning the event source. + +type EventSourceConfig struct { + BaseEventSourceConfig + 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(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") + flags.StringSlice(excludedProcesses, nil, "A list of image names to drop") +} + +func (c *EventSourceConfig) initFromViper(v *viper.Viper) { + c.EnableFileIOEvents = v.GetBool(enableFileIOEvents) + c.EnableNetEvents = v.GetBool(enableNetEvents) + c.EnableMemEvents = v.GetBool(enableMemEvents) + c.ExcludedEvents = v.GetStringSlice(excludedEvents) + c.ExcludedProcesses = v.GetStringSlice(excludedProcesses) + c.Init() +} diff --git a/pkg/config/eventsource_linux_test.go b/pkg/config/eventsource_linux_test.go new file mode 100644 index 000000000..1de2d0691 --- /dev/null +++ b/pkg/config/eventsource_linux_test.go @@ -0,0 +1,67 @@ +//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 TestEventSourceConfig(t *testing.T) { + c := NewWithOpts(WithRun()) + require.NoError(t, c.flags.Parse([]string{ + "--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.EnableFileIOEvents) + require.True(t, c.EventSource.ExcludeEvent(event.Execve)) + require.True(t, c.EventSource.ExcludeProcess(&pstypes.PS{Name: "systemd"})) +} + +func TestValidateEventSource(t *testing.T) { + file := filepath.Join(t.TempDir(), "fibratus.yml") + require.NoError(t, os.WriteFile(file, []byte(`eventsource: + enable-fileio: 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_test.go b/pkg/config/eventsource_test.go index 815fb8ff9..512979593 100644 --- a/pkg/config/eventsource_test.go +++ b/pkg/config/eventsource_test.go @@ -58,6 +58,6 @@ func TestEventSourceConfig(t *testing.T) { assert.False(t, c.EventSource.ExcludeEvent(event.CreateProcess)) - assert.True(t, c.EventSource.ExcludeImage(&pstypes.PS{Name: "svchost.exe"})) - assert.False(t, c.EventSource.ExcludeImage(&pstypes.PS{Name: "explorer.exe"})) + assert.True(t, c.EventSource.ExcludeProcess(&pstypes.PS{Name: "svchost.exe"})) + assert.False(t, c.EventSource.ExcludeProcess(&pstypes.PS{Name: "explorer.exe"})) } diff --git a/pkg/config/eventsource_windows.go b/pkg/config/eventsource_windows.go new file mode 100644 index 000000000..d8f9bc8e9 --- /dev/null +++ b/pkg/config/eventsource_windows.go @@ -0,0 +1,128 @@ +//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/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" + enableMemEvents = "eventsource.enable-mem" + enableAuditAPIEvents = "eventsource.enable-audit-api" + enableDNSEvents = "eventsource.enable-dns" + stackEnrichment = "eventsource.stack-enrichment" + bufferSize = "eventsource.buffer-size" + minBuffers = "eventsource.min-buffers" + maxBuffers = "eventsource.max-buffers" + flushInterval = "eventsource.flush-interval" + + maxBufferSize = uint32(512) +) + +var ( + defaultMinBuffers = uint32(runtime.NumCPU() * 2) + defaultMaxBuffers = uint32(runtime.NumCPU() * 8) + defaultFlushInterval = time.Second +) + +// EventSourceConfig stores different configuration options for fine-tuning the event source. +type EventSourceConfig struct { + BaseEventSourceConfig + // 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"` + // 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"` + // 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"` +} + +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(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(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(excludedProcesses, 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.EnableMemEvents = v.GetBool(enableMemEvents) + c.EnableAuditAPIEvents = v.GetBool(enableAuditAPIEvents) + c.EnableDNSEvents = v.GetBool(enableDNSEvents) + 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.ExcludedProcesses = v.GetStringSlice(excludedProcesses) + c.Init() +} diff --git a/pkg/config/filters.go b/pkg/config/filters.go index 8226b2b7f..6bf4a81b3 100644 --- a/pkg/config/filters.go +++ b/pkg/config/filters.go @@ -34,6 +34,7 @@ import ( "github.com/Masterminds/sprig/v3" "github.com/rabbitstack/fibratus/pkg/event" "github.com/rabbitstack/fibratus/pkg/util/convert" + "github.com/rabbitstack/fibratus/pkg/util/mapdecoder" "github.com/rabbitstack/fibratus/pkg/util/multierror" log "github.com/sirupsen/logrus" "github.com/spf13/viper" @@ -79,7 +80,7 @@ func (f FilterConfig) DecodeActions() ([]any, error) { actions := make([]any, 0, len(f.Action)) dec := func(m map[string]any, o any) error { - err := decode(m, &o) + err := mapdecoder.Decode(m, &o) if err != nil { return err } diff --git a/pkg/config/output.go b/pkg/config/output.go index 80d1d86d8..83901cc27 100644 --- a/pkg/config/output.go +++ b/pkg/config/output.go @@ -1,5 +1,5 @@ /* - * Copyright 2019-2020 by Nedim Sabic Sabic + * Copyright 2019-2026 by Nedim Sabic Sabic * https://www.fibratus.io * All Rights Reserved. * @@ -22,7 +22,7 @@ import ( "errors" "fmt" "reflect" - "strconv" + "strings" "github.com/rabbitstack/fibratus/pkg/outputs" "github.com/rabbitstack/fibratus/pkg/outputs/amqp" @@ -30,125 +30,78 @@ import ( "github.com/rabbitstack/fibratus/pkg/outputs/elasticsearch" "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") +var ErrNoOutputSection = errors.New("no output section in config") -var errOutputConfig = func(output string, err error) error { return fmt.Errorf("%s output invalid config: %v", output, err) } +var ErrOutputConfig = func(output outputs.Type, err error) error { + return fmt.Errorf("%s output invalid config: %v", output, err) +} + +var outs = outputs.ConfigLoaders{} -func (c *Config) tryLoadOutput() error { +func init() { + outs.Register(outputs.Console, outputs.LoadFromConfig[console.Config](outputs.Console)) + outs.Register(outputs.AMQP, outputs.LoadFromConfig[amqp.Config](outputs.AMQP)) + outs.Register(outputs.Elasticsearch, outputs.LoadFromConfig[elasticsearch.Config](outputs.Elasticsearch)) + outs.Register(outputs.HTTP, outputs.LoadFromConfig[http.Config](outputs.HTTP)) +} + +// TryLoadOutput attempts the locate an active output config and load it. +func (c *BaseConfig) TryLoadOutput() error { output := c.viper.AllSettings()["output"] if output == nil { - return errNoOutputSection + return ErrNoOutputSection } - mapping, ok := output.(map[string]interface{}) + + mapping, ok := output.(map[string]any) if !ok { return fmt.Errorf("expected map[string]interface{} type for output but found %s", reflect.TypeOf(output)) } - humNum := func(n int) string { - switch n { - case 2: - return "two" - case 3: - return "three" - case 4: - return "four" - case 5: - return "five" - case 6: - return "six" - case 7: - return "seven" - default: - return strconv.Itoa(n) - } - } - // don't permit if there are various outputs enabled at a time - activeOutputs := findActiveOutputs(mapping) - if len(activeOutputs) > 1 { - return fmt.Errorf("expected one but found %s active outputs: %s", humNum(len(activeOutputs)), activeOutputs) + active, err := findActiveOutput(mapping) + if err != nil { + return err } - for typ, config := range mapping { - switch outputs.TypeFromString(typ) { - case outputs.Console: - var consoleConfig console.Config - if err := decode(config, &consoleConfig); err != nil { - return errOutputConfig(typ, err) - } - if !consoleConfig.Enabled { - continue - } - c.Output.Type, c.Output.Output = outputs.Console, consoleConfig - case outputs.AMQP: - var amqpConfig amqp.Config - if err := decode(config, &amqpConfig); err != nil { - return errOutputConfig(typ, err) - } - if !amqpConfig.Enabled { - continue - } - c.Output.Type, c.Output.Output = outputs.AMQP, amqpConfig - case outputs.Elasticsearch: - var esConfig elasticsearch.Config - if err := decode(config, &esConfig); err != nil { - return errOutputConfig(typ, err) - } - if !esConfig.Enabled { - continue - } - c.Output.Type, c.Output.Output = outputs.Elasticsearch, esConfig - case outputs.HTTP: - var httpConfig http.Config - if err := decode(config, &httpConfig); err != nil { - return errOutputConfig(typ, err) - } - if !httpConfig.Enabled { - continue - } - c.Output.Type, c.Output.Output = outputs.HTTP, httpConfig + switch active { + case "": + c.Output.Type, c.Output.Output = outputs.Null, &null.Config{} + default: + typ := outputs.TypeFromString(active) + loader, ok := outs[typ] + if !ok { + return fmt.Errorf("unknown output type %q", typ) } - } - - // 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 + c.Output, err = loader(mapping[active]) + if err != nil { + return ErrOutputConfig(typ, err) } } - - // default to null output - if c.Output.Output == nil { - log.Warn("all outputs disabled. Defaulting to null output") - c.Output.Type, c.Output.Output = outputs.Null, &null.Config{} - } - return nil } -func findActiveOutputs(outputs map[string]interface{}) []string { - outputTypes := make([]string, 0) - for typ, rawConfig := range outputs { - enabled, ok := rawConfig.(map[string]interface{})["enabled"].(bool) - if ok && enabled { - outputTypes = append(outputTypes, typ) +// findActiveOutput returns an error if there are various outputs enabled +// at a time or either returns the active output name or an empty string if +// no outputs are enabled. +func findActiveOutput(mapping map[string]interface{}) (string, error) { + active := make([]string, 0, len(mapping)) + for typ, raw := range mapping { + output, ok := raw.(map[string]any) + if !ok { + continue + } + if enabled, _ := output["enabled"].(bool); enabled { + active = append(active, typ) } } - 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 + switch { + case len(active) > 1: + return "", fmt.Errorf("expected one but found %d active outputs: %s", len(active), strings.Join(active, ", ")) + case len(active) == 0: + return "", nil + case len(active) == 1: + return active[0], nil } - return isWinService + return "", nil } diff --git a/pkg/config/print.go b/pkg/config/print.go index 2f29c62b5..3db586699 100644 --- a/pkg/config/print.go +++ b/pkg/config/print.go @@ -26,7 +26,7 @@ import ( "strings" ) -func (c *Config) printArray(arr []interface{}) string { +func (c *BaseConfig) printArray(arr []interface{}) string { var buffer bytes.Buffer for v := range arr { fmt.Fprintf(&buffer, "%v;", v) @@ -34,7 +34,7 @@ func (c *Config) printArray(arr []interface{}) string { return buffer.String() } -func (c *Config) printMap(m map[string]interface{}) string { +func (c *BaseConfig) printMap(m map[string]interface{}) string { var buffer bytes.Buffer buffer.WriteString("[") for k, v := range m { @@ -54,7 +54,7 @@ func (c *Config) printMap(m map[string]interface{}) string { return buffer.String() } -func (c *Config) print(value interface{}) string { +func (c *BaseConfig) print(value interface{}) string { t := reflect.TypeOf(value) switch t.Kind() { case reflect.Array: @@ -66,7 +66,7 @@ func (c *Config) print(value interface{}) string { } } -func (c *Config) printLine(buffer *bytes.Buffer, maxLength int, key string, value string) { +func (c *BaseConfig) printLine(buffer *bytes.Buffer, maxLength int, key string, value string) { if value != "" { buffer.WriteString("\n\t") buffer.WriteString(key) @@ -78,7 +78,7 @@ func (c *Config) printLine(buffer *bytes.Buffer, maxLength int, key string, valu } // Print returns the string with all the config options pretty-printed. -func (c *Config) Print() string { +func (c *BaseConfig) Print() string { opts := c.viper.AllSettings() var buffer bytes.Buffer diff --git a/pkg/config/print_test.go b/pkg/config/print_test.go index e5cf70478..beea1c593 100644 --- a/pkg/config/print_test.go +++ b/pkg/config/print_test.go @@ -19,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.go b/pkg/config/schema.go new file mode 100644 index 000000000..117f8e2f0 --- /dev/null +++ b/pkg/config/schema.go @@ -0,0 +1,27 @@ +/* + * 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 _ "embed" + +//go:embed schemas/rules.schema.json +var rulesSchema string + +//go:embed schemas/macros.schema.json +var macrosSchema string diff --git a/pkg/config/schema_linux.go b/pkg/config/schema_linux.go new file mode 100644 index 000000000..8e9bd7c19 --- /dev/null +++ b/pkg/config/schema_linux.go @@ -0,0 +1,24 @@ +/* + * Copyright 2019-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 schemas/config.schema.linux.json +var configSchema string diff --git a/pkg/config/schema_windows.go b/pkg/config/schema_windows.go index a18907cc7..8afb09b43 100644 --- a/pkg/config/schema_windows.go +++ b/pkg/config/schema_windows.go @@ -1,5 +1,5 @@ /* - * Copyright 2019-2020 by Nedim Sabic Sabic + * Copyright 2019-2026 by Nedim Sabic Sabic * https://www.fibratus.io * All Rights Reserved. * @@ -18,15 +18,7 @@ package config -import ( - _ "embed" -) +import _ "embed" -//go:embed config.schema.json +//go:embed schemas/config.schema.windows.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/schemas/config.schema.linux.json b/pkg/config/schemas/config.schema.linux.json new file mode 100644 index 000000000..bf474b82d --- /dev/null +++ b/pkg/config/schemas/config.schema.linux.json @@ -0,0 +1,859 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "definitions": { + "yara": { + "$id": "#yara", + "type": "object", + "properties": { + "enabled": { + "type": "boolean" + } + } + } + }, + "type": "object", + "properties": { + "aggregator": { + "type": "object", + "properties": { + "flush-period": { + "type": "string", + "minLength": 2, + "pattern": "[0-9]+ms|s" + }, + "flush-timeout": { + "type": "string", + "minLength": 2, + "pattern": "[0-9]+s" + } + }, + "additionalProperties": false + }, + "alertsenders": { + "type": "object", + "anyOf": [ + { + "properties": { + "mail": { + "type": "object", + "properties": { + "enabled": { + "type": "boolean" + }, + "host": { + "type": "string" + }, + "port": { + "type": "number" + }, + "user": { + "type": "string" + }, + "password": { + "type": "string" + }, + "from": { + "type": "string" + }, + "to": { + "type": "array", + "items": { + "type": "string", + "format": "email" + } + }, + "content-type": { + "type": "string" + }, + "use-template": { + "type": "boolean" + } + }, + "if": { + "properties": { + "enabled": { + "const": true + } + } + }, + "then": { + "properties": { + "from": { + "type": "string", + "format": "email" + }, + "to": { + "type": "array", + "minItems": 1, + "items": { + "type": "string", + "format": "email" + } + } + } + }, + "additionalProperties": false + }, + "slack": { + "type": "object", + "properties": { + "enabled": { + "type": "boolean" + }, + "url": { + "type": "string" + }, + "workspace": { + "type": "string" + }, + "channel": { + "type": "string" + }, + "emoji": { + "type": "string" + } + }, + "if": { + "properties": { + "enabled": { + "const": true + } + } + }, + "then": { + "properties": { + "url": { + "type": "string", + "format": "uri", + "minLength": 1, + "pattern": "^(https?|http?)://" + } + } + }, + "additionalProperties": false + } + }, + "additionalProperties": false + } + ] + }, + "api": { + "type": "object", + "properties": { + "transport": { + "type": "string", + "minLength": 3 + }, + "timeout": { + "type": "string", + "minLength": 2, + "pattern": "[0-9]+s" + } + }, + "additionalProperties": false + }, + "config-file": { + "type": "string" + }, + "forward": { + "type": "boolean" + }, + "cap": { + "type": "object", + "properties": { + "file": { + "type": "string" + } + }, + "additionalProperties": false + }, + "filament": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "path": { + "type": "string" + }, + "flush-period": { + "type": "string", + "minLength": 2, + "pattern": "[0-9]+ms|s" + } + }, + "additionalProperties": false + }, + "filters": { + "type": "object", + "properties": { + "match-all": { + "type": "boolean" + }, + "rules": { + "type": "object", + "properties": { + "enabled": { + "type": "boolean" + }, + "from-paths": { + "type": [ + "array", + "null" + ], + "items": [ + { + "type": "string", + "minLength": 4 + } + ] + }, + "from-urls": { + "type": [ + "array", + "null" + ], + "items": [ + { + "type": "string", + "minLength": 8 + } + ] + } + }, + "additionalProperties": false + }, + "macros": { + "type": "object", + "properties": { + "from-paths": { + "type": [ + "array", + "null" + ], + "items": [ + { + "type": "string", + "minLength": 4 + } + ] + } + }, + "additionalProperties": false + } + }, + "additionalProperties": false + }, + "event": { + "type": "object", + "properties": { + "serialize-threads": { + "type": "boolean" + }, + "serialize-envs": { + "type": "boolean" + } + }, + "additionalProperties": false + }, + "eventsource": { + "type": "object", + "properties": { + "enable-thread": { + "type": "boolean" + }, + "enable-fileio": { + "type": "boolean" + }, + "enable-net": { + "type": "boolean" + }, + "enable-mem": { + "type": "boolean" + }, + "blacklist": { + "type": "object", + "properties": { + "events": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "execve", + "exit", + "clone", + "openat", + "unlink", + "rename", + "connect", + "accept", + "mmap", + "process_vm_read", + "process_vm_write", + "kill", + "ptrace", + "prctl" + ] + } + }, + "images": { + "type": "array", + "items": { + "type": "string", + "minLength": 1 + } + } + }, + "additionalProperties": false + } + }, + "additionalProperties": false + }, + "logging": { + "type": "object", + "properties": { + "level": { + "type": "string" + }, + "max-age": { + "type": "integer" + }, + "max-backups": { + "type": "integer", + "minimum": 1 + }, + "max-size": { + "type": "integer", + "minimum": 1 + }, + "formatter": { + "type": "string", + "enum": [ + "json", + "text" + ] + }, + "path": { + "type": "string" + }, + "log-stdout": { + "type": "boolean" + } + }, + "additionalProperties": false + }, + "output": { + "type": "object", + "anyOf": [ + { + "properties": { + "console": { + "type": "object", + "properties": { + "enabled": { + "type": "boolean" + }, + "colorize": { + "type": "boolean" + }, + "format": { + "type": "string", + "enum": [ + "json", + "pretty" + ] + }, + "template": { + "type": "string" + }, + "kv-delimiter": { + "type": "string" + } + }, + "additionalProperties": false + }, + "elasticsearch": { + "type": "object", + "properties": { + "enabled": { + "type": "boolean" + }, + "servers": { + "type": "array", + "items": [ + { + "type": "string", + "minItems": 1, + "format": "uri", + "minLength": 1, + "maxLength": 255, + "pattern": "^(https?|http?)://" + } + ] + }, + "timeout": { + "type": "string" + }, + "index-name": { + "type": "string", + "minLength": 1 + }, + "template-config": { + "type": "string" + }, + "template-name": { + "type": "string", + "minLength": 1 + }, + "healthcheck": { + "type": "boolean" + }, + "bulk-workers": { + "type": "integer", + "minimum": 1 + }, + "sniff": { + "type": "boolean" + }, + "trace-log": { + "type": "boolean" + }, + "gzip-compression": { + "type": "boolean" + }, + "healthcheck-interval": { + "type": "string", + "minLength": 2, + "pattern": "[0-9]+s|m}" + }, + "healthcheck-timeout": { + "type": "string", + "minLength": 2, + "pattern": "[0-9]+s|m}" + }, + "flush-period": { + "type": "string", + "minLength": 2, + "pattern": "[0-9]+s|m}" + }, + "username": { + "type": "string" + }, + "password": { + "type": "string" + }, + "tls-key": { + "type": "string" + }, + "tls-cert": { + "type": "string" + }, + "tls-ca": { + "type": "string" + }, + "tls-insecure-skip-verify": { + "type": "boolean" + } + }, + "additionalProperties": false + }, + "amqp": { + "type": "object", + "properties": { + "enabled": { + "type": "boolean" + }, + "url": { + "type": "string", + "format": "uri", + "minLength": 1, + "maxLength": 255, + "pattern": "^(amqps?|amqp?)://" + }, + "timeout": { + "type": "string", + "minLength": 2, + "pattern": "[0-9]+s|m}" + }, + "exchange": { + "type": "string", + "minLength": 1 + }, + "exchange-type": { + "type": "string", + "enum": [ + "direct", + "topic", + "fanout", + "header", + "x-consistent-hash" + ] + }, + "routing-key": { + "type": "string", + "minLength": 1 + }, + "delivery-mode": { + "type": "string", + "enum": [ + "transient", + "persistent" + ] + }, + "vhost": { + "type": "string", + "minLength": 1 + }, + "passive": { + "type": "boolean" + }, + "durable": { + "type": "boolean" + }, + "username": { + "type": "string" + }, + "password": { + "type": "string" + }, + "tls-key": { + "type": "string" + }, + "tls-cert": { + "type": "string" + }, + "tls-ca": { + "type": "string" + }, + "tls-insecure-skip-verify": { + "type": "boolean" + }, + "headers": { + "type": "object", + "additionalProperties": true + } + }, + "additionalProperties": false + }, + "http": { + "type": "object", + "properties": { + "enabled": { + "type": "boolean" + }, + "endpoints": { + "type": "array", + "items": [ + { + "type": "string", + "minItems": 1, + "format": "uri", + "minLength": 1, + "maxLength": 255, + "pattern": "^(https?|http?)://" + } + ] + }, + "timeout": { + "type": "string", + "minLength": 2, + "pattern": "[0-9]+s|m}" + }, + "method": { + "type": "string", + "enum": [ + "POST", + "PUT" + ] + }, + "serializer": { + "type": "string", + "enum": [ + "json" + ] + }, + "enable-gzip": { + "type": "boolean" + }, + "proxy-url": { + "type": "string" + }, + "proxy-username": { + "type": "string" + }, + "proxy-password": { + "type": "string" + }, + "username": { + "type": "string" + }, + "password": { + "type": "string" + }, + "tls-key": { + "type": "string" + }, + "tls-cert": { + "type": "string" + }, + "tls-ca": { + "type": "string" + }, + "tls-insecure-skip-verify": { + "type": "boolean" + }, + "headers": { + "type": "object", + "additionalProperties": true + } + }, + "additionalProperties": false + } + }, + "additionalProperties": false + } + ] + }, + "transformers": { + "type": "object", + "anyOf": [ + { + "properties": { + "remove": { + "type": "object", + "properties": { + "enabled": { + "type": "boolean" + }, + "params": { + "type": "array", + "items": [ + { + "type": "string" + } + ] + } + }, + "if": { + "properties": { + "enabled": { + "const": true + } + } + }, + "then": { + "properties": { + "params": { + "type": "array", + "minItems": 1, + "items": [ + { + "type": "string" + } + ] + } + } + }, + "additionalProperties": false + }, + "rename": { + "type": "object", + "properties": { + "enabled": { + "type": "boolean" + }, + "params": { + "type": "array", + "items": [ + { + "type": "object", + "properties": { + "old": { + "type": "string", + "minLength": 1 + }, + "new": { + "type": "string", + "minLength": 1 + } + }, + "additionalProperties": false + } + ] + } + }, + "if": { + "properties": { + "enabled": { + "const": true + } + } + }, + "then": { + "properties": { + "params": { + "minItems": 1 + } + } + }, + "additionalProperties": false + }, + "replace": { + "type": "object", + "properties": { + "enabled": { + "type": "boolean" + }, + "replacements": { + "type": "array", + "items": [ + { + "type": "object", + "properties": { + "param": { + "type": "string", + "minLength": 1 + }, + "old": { + "type": "string", + "minLength": 1 + }, + "new": { + "type": "string" + } + }, + "additionalProperties": false + } + ] + } + }, + "if": { + "properties": { + "enabled": { + "const": true + } + } + }, + "then": { + "properties": { + "replacements": { + "minItems": 1 + } + } + }, + "additionalProperties": false + }, + "tags": { + "type": "object", + "properties": { + "enabled": { + "type": "boolean" + }, + "tags": { + "type": "array", + "items": [ + { + "type": "object", + "properties": { + "key": { + "type": "string", + "minLength": 1 + }, + "value": { + "type": "string", + "minLength": 1 + } + }, + "additionalProperties": false + } + ] + } + }, + "if": { + "properties": { + "enabled": { + "const": true + } + } + }, + "then": { + "properties": { + "tags": { + "minItems": 1 + } + } + }, + "additionalProperties": false + }, + "trim": { + "type": "object", + "properties": { + "enabled": { + "type": "boolean" + }, + "prefixes": { + "type": "array", + "items": [ + { + "type": "object", + "properties": { + "param": { + "type": "string", + "minLength": 1 + }, + "trim": { + "type": "string", + "minLength": 1 + } + }, + "additionalProperties": false + } + ] + }, + "suffixes": { + "type": "array", + "items": [ + { + "type": "object", + "properties": { + "param": { + "type": "string", + "minLength": 1 + }, + "trim": { + "type": "string", + "minLength": 1 + } + }, + "additionalProperties": false + } + ] + } + }, + "if": { + "properties": { + "enabled": { + "const": true + } + } + }, + "then": { + "properties": { + "suffixes": { + "minItems": 1 + }, + "prefixes": { + "minItems": 1 + } + } + }, + "additionalProperties": false + } + }, + "additionalProperties": false + } + ] + } + }, + "additionalProperties": false +} \ No newline at end of file diff --git a/pkg/config/config.schema.json b/pkg/config/schemas/config.schema.windows.json similarity index 100% rename from pkg/config/config.schema.json rename to pkg/config/schemas/config.schema.windows.json diff --git a/pkg/config/macros.schema.json b/pkg/config/schemas/macros.schema.json similarity index 100% rename from pkg/config/macros.schema.json rename to pkg/config/schemas/macros.schema.json diff --git a/pkg/config/rules.schema.json b/pkg/config/schemas/rules.schema.json similarity index 100% rename from pkg/config/rules.schema.json rename to pkg/config/schemas/rules.schema.json diff --git a/pkg/config/transformer.go b/pkg/config/transformer.go index 24b5df7d6..0cef4ca38 100644 --- a/pkg/config/transformer.go +++ b/pkg/config/transformer.go @@ -20,101 +20,53 @@ 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) } +var ErrTransformerConfig = func(t string, err error) error { return fmt.Errorf("%s transformer invalid config: %v", t, err) } + +var trans = transformers.ConfigLoaders{} -func (c *Config) tryLoadTransformers() error { +func init() { + trans.Register(transformers.Remove, transformers.LoadFromConfig(transformers.Remove, func(c remove.Config) bool { return c.Enabled })) + trans.Register(transformers.Rename, transformers.LoadFromConfig(transformers.Rename, func(c rename.Config) bool { return c.Enabled })) + trans.Register(transformers.Replace, transformers.LoadFromConfig(transformers.Replace, func(c replace.Config) bool { return c.Enabled })) + trans.Register(transformers.Trim, transformers.LoadFromConfig(transformers.Trim, func(c trim.Config) bool { return c.Enabled })) + trans.Register(transformers.Tags, transformers.LoadFromConfig(transformers.Tags, func(c tags.Config) bool { return c.Enabled })) +} + +// TryLoadTransformers attempts to load all registered transformer configs. +func (c *BaseConfig) TryLoadTransformers() error { transforms := c.viper.AllSettings()["transformers"] if transforms == nil { return nil } - mapping, ok := transforms.(map[string]interface{}) + mapping, ok := transforms.(map[string]any) if !ok { return fmt.Errorf("expected map[string]interface{} type for transformers but found %s", reflect.TypeOf(transforms)) } - configs := make([]transformers.Config, 0) - - for typ, config := range mapping { - switch typ { - case "remove": - var removeConfig remove.Config - if err := decode(config, &removeConfig); err != nil { - return errTransformerConfig(typ, err) - } - if !removeConfig.Enabled { - continue - } - config := transformers.Config{ - Type: transformers.Remove, - Transformer: removeConfig, - } - configs = append(configs, config) - - case "rename": - var renameConfig rename.Config - if err := decode(config, &renameConfig); err != nil { - return errTransformerConfig(typ, err) - } - if !renameConfig.Enabled { - continue - } - config := transformers.Config{ - Type: transformers.Rename, - Transformer: renameConfig, - } - configs = append(configs, config) - - case "replace": - var replaceConfig replace.Config - if err := decode(config, &replaceConfig); err != nil { - return errTransformerConfig(typ, err) - } - if !replaceConfig.Enabled { - continue - } - config := transformers.Config{ - Type: transformers.Replace, - Transformer: replaceConfig, - } - configs = append(configs, config) - - case "trim": - var trimConfig trim.Config - if err := decode(config, &trimConfig); err != nil { - return errTransformerConfig(typ, err) - } - if !trimConfig.Enabled { - continue - } - config := transformers.Config{ - Type: transformers.Trim, - Transformer: trimConfig, - } - configs = append(configs, config) - - case "tags": - var tagsConfig tags.Config - if err := decode(config, &tagsConfig); err != nil { - return errTransformerConfig(typ, err) - } - if !tagsConfig.Enabled { - continue - } - config := transformers.Config{ - Type: transformers.Tags, - Transformer: tagsConfig, - } - configs = append(configs, config) + configs := make([]transformers.Config, 0, len(mapping)) + for typ, raw := range mapping { + loader, ok := trans[transformers.TypeFromString(typ)] + if !ok { + return fmt.Errorf("unknown transformer type %q", typ) + } + cfg, enabled, err := loader(raw) + if err != nil { + return ErrTransformerConfig(typ, err) + } + if !enabled { + continue } + configs = append(configs, cfg) } c.Transformers = configs diff --git a/pkg/config/transformer_test.go b/pkg/config/transformer_test.go index 9000fd3d0..f16d87c19 100644 --- a/pkg/config/transformer_test.go +++ b/pkg/config/transformer_test.go @@ -19,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/event/batch_linux_test.go b/pkg/event/batch_linux_test.go new file mode 100644 index 000000000..84a9d609c --- /dev/null +++ b/pkg/event/batch_linux_test.go @@ -0,0 +1,37 @@ +//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/require" +) + +func TestBatchMarshalJSON(t *testing.T) { + batch := NewBatch(&Event{PID: 42, Type: Execve}, &Event{PID: 43, Type: Exit}) + require.EqualValues(t, 2, batch.Len()) + + 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 100% rename from pkg/event/batch_test.go rename to pkg/event/batch_windows_test.go diff --git a/pkg/event/enum.go b/pkg/event/enum_windows.go similarity index 100% rename from pkg/event/enum.go rename to pkg/event/enum_windows.go diff --git a/pkg/event/event.go b/pkg/event/event.go index ba1b03039..6d334caca 100644 --- a/pkg/event/event.go +++ b/pkg/event/event.go @@ -95,8 +95,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 new file mode 100644 index 000000000..275dbe9c3 --- /dev/null +++ b/pkg/event/event_linux.go @@ -0,0 +1,62 @@ +//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 ( + "os" + + "github.com/rabbitstack/fibratus/pkg/event/params" + "golang.org/x/sys/unix" +) + +// IsCreateProcess reports whether clone creates a new process. +func (e *Event) IsCreateProcess() bool { + return e.Type == Clone && e.Params.TryGetUint64(params.CloneFlags)&unix.CLONE_THREAD == 0 +} + +// 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)&unix.CLONE_THREAD != 0 +} + +// 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) +} + +// DropCurrentProc determines if events generated by the Fibratus process are dropped. +var DropCurrentProc = true + +var currentPid = uint32(os.Getpid()) + +// IsDropped reports whether the event should be omitted from the output queue. +func (e *Event) IsDropped(_ bool) bool { + return DropCurrentProc && e.PID == currentPid +} + +// IsStackWalk reports whether the event is a stack walk record. +func (e *Event) IsStackWalk() bool { return false } + +// IsState reports whether the event is used only for state management. +func (e *Event) IsState() bool { return false } diff --git a/pkg/event/event_linux_test.go b/pkg/event/event_linux_test.go new file mode 100644 index 000000000..4dc19e716 --- /dev/null +++ b/pkg/event/event_linux_test.go @@ -0,0 +1,57 @@ +//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" + + "github.com/rabbitstack/fibratus/pkg/event/params" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "golang.org/x/sys/unix" +) + +func TestParamBasics(t *testing.T) { + 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.String, "bash") + assert.Equal(t, "bash", pars.MustGetString(params.ProcessName)) +} + +func TestEventTypeHelpers(t *testing.T) { + e := &Event{Type: Execve, PID: 1} + assert.False(t, e.IsCreateProcess()) + assert.Equal(t, Process, e.Category()) + assert.Equal(t, Execve, e.Type) + + 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, unix.CLONE_THREAD) + assert.False(t, threadClone.IsCreateProcess()) + assert.True(t, threadClone.IsCreateThread()) +} diff --git a/pkg/event/flags.go b/pkg/event/flags.go index 693a56ba1..8a77a812e 100644 --- a/pkg/event/flags.go +++ b/pkg/event/flags.go @@ -18,14 +18,9 @@ package event -import ( - "strings" +import "strings" - "github.com/rabbitstack/fibratus/pkg/sys" - "golang.org/x/sys/windows" -) - -// 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 @@ -35,240 +30,27 @@ 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 { - var ( - n strings.Builder - s 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 - } +// String returns the names of all flags in the bitmask, separated by pipes. +func (flags ParamFlags) String(value uint64) string { + if value == 0 { + return "" } - 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 + var b strings.Builder + b.Grow(64) // rough estimate -// 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}, -} + for _, flag := range flags { + if flag.eval(value) { + if b.Len() > 0 { + b.WriteByte('|') + } + b.WriteString(flag.Name) + value &= ^flag.Value + } + } -// 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 b.String() } diff --git a/pkg/event/flags_test.go b/pkg/event/flags_test.go index 48e6351dd..78fdc6f5c 100644 --- a/pkg/event/flags_test.go +++ b/pkg/event/flags_test.go @@ -21,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 7a3e0361b..0b057fc2f 100644 --- a/pkg/event/formatter.go +++ b/pkg/event/formatter.go @@ -68,9 +68,11 @@ const ( var ( // tmplRegexp defines the regular expression for parsing template fields. tmplRegexp = regexp.MustCompile(`({{2}.*?}{2})`) + // tmplNormRegepx defines the regular expression for normalizing the template. This basically consists in removing // the brackets and trailing/leading spaces from the field name. tmplNormRegexp = regexp.MustCompile(`({{2}\s*([A-Za-z.]+)\s*}{2})`) + // tmplExpandParamsRegexp determines whether Params. fields are expanded tmplExpandParamsRegexp = regexp.MustCompile(`{{\s*.Params.\S+}}`) ) @@ -87,7 +89,6 @@ var fields = map[string]bool{ exe: true, cmd: true, tid: true, - sid: true, proc: true, cat: true, desc: true, @@ -96,7 +97,6 @@ var fields = map[string]bool{ parameters: true, meta: true, host: true, - pe: true, cstack: true, } @@ -109,13 +109,14 @@ func hintFields() string { return strings.Join(s, " ") } -// Formatter deals with producing event's output that is dictated by the template. +// Formatter contains the core functionality substituting template tags +// with the corresponding values from the map and returning the result. type Formatter struct { t *fasttemplate.Template expandParamsDot bool } -// NewFormatter builds a new instance of event's formatter. +// NewFormatter builds a new instance of the event formatter. func NewFormatter(template string) (*Formatter, error) { // check basic template format and ensure all fields // defined in the template are known to us @@ -143,8 +144,9 @@ func NewFormatter(template string) (*Formatter, error) { } } - // user might define the tag such as `{{ .Seq }}` or {{ .Seq}}`. We have to make sure - // inner spaces are removed before building the fast template instance + // user might define the tag such as `{{ .Seq }}` or {{ .Seq}}`. + // We have to make sure inner spaces are removed before building + // the fast template instance norm := normalizeTemplate(template) t, err := fasttemplate.NewTemplate(norm, startTag, endTag) if err != nil { @@ -157,6 +159,23 @@ func NewFormatter(template string) (*Formatter, error) { }, nil } +// eventMap returns the map populated with canonical event fields. +func (f *Formatter) eventMap(evt *Event) map[string]any { + return map[string]any{ + 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(), + } +} + // ColorFormatter wraps a Formatter and re-renders each template tag with // ANSI colour codes before it is substituted into the output string. // @@ -203,95 +222,6 @@ func (f *ColorFormatter) Format(e *Event) []byte { return bytes.TrimRight(b.Bytes(), "\n") } -// colourTag maps a bare tag name to its coloured string representation. -func (f *ColorFormatter) colourTag(tag string, e *Event) string { - switch tag { - case seq: - // sequence number is ok to render as dim gray - return colorizer.SpanDim(colorizer.Span(colorizer.Gray, strconv.FormatUint(e.Seq, 10))) - case ts: - return f.colourTimestamp(e) - case cpu: - return colorizer.Span(colorizer.Yellow, strconv.FormatUint(uint64(e.CPU), 10)) - case proc: - // render process name with bold green as it is the most important - // identity anchor on the line. Analysts scan for it first. - ps := e.PS - if ps == nil { - return colorizer.Span(colorizer.Gray, "N/A") - } - return colorizer.SpanBold(colorizer.Green, ps.Name) - case pid: - return colorizer.Span(colorizer.Green, strconv.FormatUint(uint64(e.PID), 10)) - case ppid: - ps := e.PS - if ps == nil { - return colorizer.Span(colorizer.Gray, "N/A") - } - return colorizer.Span(colorizer.Green, strconv.FormatUint(uint64(ps.Ppid), 10)) - case tid: - return colorizer.Span(colorizer.Green, strconv.FormatUint(uint64(e.Tid), 10)) - case exe: - ps := e.PS - if ps == nil { - return colorizer.Span(colorizer.Gray, "N/A") - } - return colorizer.Span(colorizer.White, ps.Exe) - case pexe: - ps := e.PS - if ps == nil || ps.Parent == nil { - return colorizer.Span(colorizer.Gray, "N/A") - } - return colorizer.Span(colorizer.White, ps.Parent.Exe) - case cmd: - ps := e.PS - if ps == nil { - return colorizer.Span(colorizer.Gray, "N/A") - } - return colorizer.Span(colorizer.White, ps.Cmdline) - case pcmd: - ps := e.PS - if ps == nil || ps.Parent == nil { - return colorizer.Span(colorizer.Gray, "N/A") - } - return colorizer.Span(colorizer.White, ps.Parent.Cmdline) - case cwd: - ps := e.PS - if ps == nil { - return colorizer.Span(colorizer.Gray, "N/A") - } - 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 { - return colorizer.Span(colorizer.Gray, "N/A") - } - return colorizer.Span(colorizer.Green, ps.Parent.Name) - case typ: - return e.Type.color() - case cat: - return colorizer.Span(colorizer.Magenta, e.Category().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 "" -} - // colourTimestamp renders the timestamp tag with: // - date in blue, time in cyan, tz components dim gray // - a Δt suffix showing the gap from the previous event, colour-coded by diff --git a/pkg/event/formatter_linux.go b/pkg/event/formatter_linux.go new file mode 100644 index 000000000..8b4a587af --- /dev/null +++ b/pkg/event/formatter_linux.go @@ -0,0 +1,138 @@ +//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 ( + "fmt" + "strconv" + + "github.com/rabbitstack/fibratus/pkg/util/colorizer" +) + +// Format applies the template on the provided event. +func (f *Formatter) Format(evt *Event) []byte { + if evt == nil { + return []byte{} + } + + values := f.eventMap(evt) + + 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 + parent := ps.Parent + + if parent != nil { + values[pproc] = parent.Name + values[pexe] = parent.Exe + values[pcmd] = parent.Cmdline + } + } + + if f.expandParamsDot { + for _, par := range evt.Params { + values[".Params."+caser.String(par.Name)] = par.String() + } + } + + return f.t.ExecuteString(values) +} + +// colourTag maps a bare tag name to its coloured string representation. +func (f *ColorFormatter) colourTag(tag string, e *Event) string { + switch tag { + case seq: + // sequence number is ok to render as dim gray + return colorizer.SpanDim(colorizer.Span(colorizer.Gray, strconv.FormatUint(e.Seq, 10))) + case ts: + return f.colourTimestamp(e) + case cpu: + return colorizer.Span(colorizer.Yellow, strconv.FormatUint(uint64(e.CPU), 10)) + case proc: + // render process name with bold green as it is the most important + // identity anchor on the line. Analysts scan for it first. + ps := e.PS + if ps == nil { + return colorizer.Span(colorizer.Gray, "N/A") + } + return colorizer.SpanBold(colorizer.Green, ps.Name) + case pid: + return colorizer.Span(colorizer.Green, strconv.FormatUint(uint64(e.PID), 10)) + case ppid: + ps := e.PS + if ps == nil { + return colorizer.Span(colorizer.Gray, "N/A") + } + return colorizer.Span(colorizer.Green, strconv.FormatUint(uint64(ps.Ppid), 10)) + case tid: + return colorizer.Span(colorizer.Green, strconv.FormatUint(uint64(e.Tid), 10)) + case exe: + ps := e.PS + if ps == nil { + return colorizer.Span(colorizer.Gray, "N/A") + } + return colorizer.Span(colorizer.White, ps.Exe) + case pexe: + ps := e.PS + if ps == nil || ps.Parent == nil { + return colorizer.Span(colorizer.Gray, "N/A") + } + return colorizer.Span(colorizer.White, ps.Parent.Exe) + case cmd: + ps := e.PS + if ps == nil { + return colorizer.Span(colorizer.Gray, "N/A") + } + return colorizer.Span(colorizer.White, ps.Cmdline) + case pcmd: + ps := e.PS + if ps == nil || ps.Parent == nil { + return colorizer.Span(colorizer.Gray, "N/A") + } + return colorizer.Span(colorizer.White, ps.Parent.Cmdline) + case cwd: + ps := e.PS + if ps == nil { + return colorizer.Span(colorizer.Gray, "N/A") + } + return colorizer.Span(colorizer.White, ps.Cwd) + case pproc: + ps := e.PS + if ps == nil || ps.Parent == nil { + return colorizer.Span(colorizer.Gray, "N/A") + } + return colorizer.Span(colorizer.Green, ps.Parent.Name) + case typ: + return e.Type.color() + case cat: + return colorizer.Span(colorizer.Magenta, e.Category().String()) + case parameters: + return e.Params.Colorize() + case cstack: + return fmt.Sprintf("\n%s", e.Callstack.Colorize()) + } + + return "" +} diff --git a/pkg/event/formatter_linux_test.go b/pkg/event/formatter_linux_test.go new file mode 100644 index 000000000..2f534f9a6 --- /dev/null +++ b/pkg/event/formatter_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 event + +import ( + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestFormatter(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, + } + 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 3c55f3f54..30006a8e7 100644 --- a/pkg/event/formatter_windows.go +++ b/pkg/event/formatter_windows.go @@ -19,29 +19,25 @@ package event import ( + "fmt" "strconv" + + "github.com/rabbitstack/fibratus/pkg/util/colorizer" ) +func init() { + fields[sid] = true + fields[pe] = true +} + // 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(), - } - // add process metadata + values := f.eventMap(evt) + ps := evt.PS if ps != nil { values[proc] = ps.Name @@ -51,23 +47,23 @@ func (f *Formatter) Format(evt *Event) []byte { 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 + 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() } @@ -75,3 +71,90 @@ func (f *Formatter) Format(evt *Event) []byte { return f.t.ExecuteString(values) } + +// colourTag maps a bare tag name to its coloured string representation. +func (f *ColorFormatter) colourTag(tag string, e *Event) string { + switch tag { + case seq: + // sequence number is ok to render as dim gray + return colorizer.SpanDim(colorizer.Span(colorizer.Gray, strconv.FormatUint(e.Seq, 10))) + case ts: + return f.colourTimestamp(e) + case cpu: + return colorizer.Span(colorizer.Yellow, strconv.FormatUint(uint64(e.CPU), 10)) + case proc: + // render process name with bold green as it is the most important + // identity anchor on the line. Analysts scan for it first. + ps := e.PS + if ps == nil { + return colorizer.Span(colorizer.Gray, "N/A") + } + return colorizer.SpanBold(colorizer.Green, ps.Name) + case pid: + return colorizer.Span(colorizer.Green, strconv.FormatUint(uint64(e.PID), 10)) + case ppid: + ps := e.PS + if ps == nil { + return colorizer.Span(colorizer.Gray, "N/A") + } + return colorizer.Span(colorizer.Green, strconv.FormatUint(uint64(ps.Ppid), 10)) + case tid: + return colorizer.Span(colorizer.Green, strconv.FormatUint(uint64(e.Tid), 10)) + case exe: + ps := e.PS + if ps == nil { + return colorizer.Span(colorizer.Gray, "N/A") + } + return colorizer.Span(colorizer.White, ps.Exe) + case pexe: + ps := e.PS + if ps == nil || ps.Parent == nil { + return colorizer.Span(colorizer.Gray, "N/A") + } + return colorizer.Span(colorizer.White, ps.Parent.Exe) + case cmd: + ps := e.PS + if ps == nil { + return colorizer.Span(colorizer.Gray, "N/A") + } + return colorizer.Span(colorizer.White, ps.Cmdline) + case pcmd: + ps := e.PS + if ps == nil || ps.Parent == nil { + return colorizer.Span(colorizer.Gray, "N/A") + } + return colorizer.Span(colorizer.White, ps.Parent.Cmdline) + case cwd: + ps := e.PS + if ps == nil { + return colorizer.Span(colorizer.Gray, "N/A") + } + return colorizer.Span(colorizer.White, ps.Cwd) + case pproc: + ps := e.PS + if ps == nil || ps.Parent == nil { + return colorizer.Span(colorizer.Gray, "N/A") + } + return colorizer.Span(colorizer.Green, ps.Parent.Name) + case sid: + if e.PS == nil { + return colorizer.Span(colorizer.Gray, "N/A") + } + return colorizer.Span(colorizer.Gray, e.PS.SID) + case pe: + if e.PS == nil || e.PS.PE == nil { + return colorizer.Span(colorizer.Gray, "N/A") + } + return colorizer.Span(colorizer.Magenta, e.PS.PE.String()) + case typ: + return e.Type.color() + case cat: + return colorizer.Span(colorizer.Magenta, e.Category().String()) + case parameters: + return e.Params.Colorize() + case cstack: + return fmt.Sprintf("\n%s", e.Callstack.Colorize()) + } + + return "" +} diff --git a/pkg/event/formatter_test.go b/pkg/event/formatter_windows_test.go similarity index 100% rename from pkg/event/formatter_test.go rename to pkg/event/formatter_windows_test.go diff --git a/pkg/event/marshaller_linux.go b/pkg/event/marshaller_linux.go new file mode 100644 index 000000000..44853f526 --- /dev/null +++ b/pkg/event/marshaller_linux.go @@ -0,0 +1,45 @@ +//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" + "fmt" + + capver "github.com/rabbitstack/fibratus/pkg/cap/version" +) + +// SerializeEnvs indicates if environment variables are serialized with process state. +var SerializeEnvs bool + +// 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 an event from a capture buffer. +func (e *Event) UnmarshalRaw(_ []byte, _ capver.Version) error { + return fmt.Errorf("event capture 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..a334b4133 --- /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 TestMarshalJSON(t *testing.T) { + event := &Event{PID: 42, Tid: 43, Type: Execve} + 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_test.go b/pkg/event/marshaller_windows_test.go similarity index 100% rename from pkg/event/marshaller_test.go rename to pkg/event/marshaller_windows_test.go diff --git a/pkg/event/metainfo.go b/pkg/event/metainfo.go new file mode 100644 index 000000000..8ab1384b5 --- /dev/null +++ b/pkg/event/metainfo.go @@ -0,0 +1,76 @@ +/* + * 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 "slices" + +// Flags represents the event flags +type Flags uint8 + +// 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, network) + Category Category + // Subcategory designates the event subcategory if any. For example, the network category + // can be further subcategorized, such as DNS subcategory. + Subcategory Subcategory + // Source describes the event source origin for this event. For example, if it was captured + // from the NT Kernel Logger or eBPF raw syscall tracepoint. + Source Source + // Description is the short explanation that describes the purpose of the event. + Description string + // Flags describes additional properties of the event. + Flags Flags +} + +// All returns all event types. +func AllTypes() []Type { + types := make([]Type, 0) + for i := range table { + if Type(i) == Unknown { + continue + } + types = append(types, Type(i)) + } + return types +} + +// GetTypeInfo returns metadata about the specified event type. +func GetTypeInfo(typ Type) Info { + return table[typ] +} + +// NameToType converts a human-readable event name to its internal type representation. +func ParseType(s string) (Type, bool) { + i := slices.IndexFunc(table[:], func(info Info) bool { + return info.Name == s + }) + if i == -1 { + return Unknown, false + } + return Type(i), true +} + +// IsKnown indicates if the event type is known given the event name. +func IsTypeKnown(s string) (exists bool) { + _, exists = ParseType(s) + return +} diff --git a/pkg/event/metainfo_linux.go b/pkg/event/metainfo_linux.go new file mode 100644 index 000000000..fee0bdfdb --- /dev/null +++ b/pkg/event/metainfo_linux.go @@ -0,0 +1,55 @@ +//go:build linux + +/* + * Copyright 2026 by Mostafa Moradian + * 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 ( + "cmp" + "slices" +) + +var table = [MaxEvent]Info{ + Execve: {Name: "execve", Category: Process, Source: RawSyscallTracepoint, Description: "Executes a program"}, + Exit: {Name: "exit", Category: Process, Source: RawSyscallTracepoint, Description: "Exit all threads in a process"}, + Openat: {Name: "openat", Category: File, Source: RawSyscallTracepoint, Description: "Opens or creates a file"}, + Unlink: {Name: "unlink", Category: File, Source: RawSyscallTracepoint, Description: "Removes a directory entry"}, + Rename: {Name: "rename", Category: File, Source: RawSyscallTracepoint, Description: "Renames a file or directory"}, + Connect: {Name: "connect", Category: Network, Source: RawSyscallTracepoint, Description: "Initiates a socket connection"}, + Accept: {Name: "accept", Category: Network, Source: RawSyscallTracepoint, Description: "Accepts a socket connection"}, + Mmap: {Name: "mmap", Category: Memory, Source: RawSyscallTracepoint, Description: "Maps files or devices into memory"}, + ProcessVMRead: {Name: "process_vm_read", Category: Memory, Source: RawSyscallTracepoint, Description: "Reads memory from another process"}, + ProcessVMWrite: {Name: "process_vm_write", Category: Memory, Source: RawSyscallTracepoint, Description: "Writes memory into another process"}, + Kill: {Name: "kill", Category: Process, Source: RawSyscallTracepoint, Description: "Sends a signal to a process"}, + Ptrace: {Name: "ptrace", Category: Process, Source: RawSyscallTracepoint, Description: "Traces or controls another process"}, + Prctl: {Name: "prctl", Category: Process, Source: RawSyscallTracepoint, Description: "Performs a process-control operation"}, +} + +// GetTypesInfo returns event types metadata. +func GetTypesInfo() []Info { + t := table[:] + t = slices.DeleteFunc(t, func(info Info) bool { + return info.Name == "" + }) + slices.SortFunc(t, func(a, b Info) int { + return cmp.Or(cmp.Compare(a.Category, b.Category), cmp.Compare(a.Name, b.Name)) + }) + return t +} diff --git a/pkg/event/metainfo_windows.go b/pkg/event/metainfo_windows.go index 4817fbcd2..121bfdd0d 100644 --- a/pkg/event/metainfo_windows.go +++ b/pkg/event/metainfo_windows.go @@ -23,9 +23,6 @@ import ( "slices" ) -// Flags represents the event flags -type Flags uint8 - const ( // OnlyState indicates the event produces internal state // and is never published to the event stream. @@ -40,24 +37,6 @@ const ( WaitStack Flags = 1 << 3 ) -// 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, network) - Category Category - // Subcategory designates the event subcategory if any. For example, the network category - // can be further subcategorized, such as DNS subcategory. - Subcategory Subcategory - // Source describes the event source origin for this event. For example, if it was captured - // from the NT Kernel Logger or a different event source. - Source Source - // Description is the short explanation that describes the purpose of the event. - Description string - // Flags describes additional properties of the event. - Flags Flags -} - var table = [MaxEvent]Info{ CreateProcess: {Name: "CreateProcess", Category: Process, Source: SystemLogger, Description: "Creates a new process and its primary thread", Flags: WaitStack}, TerminateProcess: {Name: "TerminateProcess", Category: Process, Source: SystemLogger, Description: "Terminates the process and all of its threads"}, @@ -122,23 +101,6 @@ var table = [MaxEvent]Info{ CreateSymbolicLinkObject: {Name: "CreateSymbolicLinkObject", Category: Object, Source: SecurityTelemetryLogger, Description: "Creates the symbolic link within the object manager directory"}, } -// All returns all event types. -func AllTypes() []Type { - types := make([]Type, 0) - for i := range table { - if Type(i) == Unknown { - continue - } - types = append(types, Type(i)) - } - return types -} - -// GetTypeInfo returns metadata about the specified event type. -func GetTypeInfo(typ Type) Info { - return table[typ] -} - // GetTypesInfo returns event types metadata excluding only-state events. func GetTypesInfo() []Info { t := table[:] @@ -150,20 +112,3 @@ func GetTypesInfo() []Info { }) return t } - -// NameToType converts a human-readable event name to its internal type representation. -func ParseType(s string) (Type, bool) { - i := slices.IndexFunc(table[:], func(info Info) bool { - return info.Name == s - }) - if i == -1 { - return Unknown, false - } - return Type(i), true -} - -// IsKnown indicates if the event type is known given the event name. -func IsTypeKnown(s string) (exists bool) { - _, exists = ParseType(s) - return -} diff --git a/pkg/event/param.go b/pkg/event/param.go index 58f003865..11d0ea747 100644 --- a/pkg/event/param.go +++ b/pkg/event/param.go @@ -26,11 +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" "golang.org/x/text/language" @@ -108,70 +104,9 @@ func (p Param) IsNumber() bool { p.Type == params.Uint8 || p.Type == params.Uint16 || p.Type == params.Uint32 || p.Type == params.Uint64 } -// CaptureType returns the event type saved inside the capture file. -// Captures usually override the type of the parameter to provide -// consistent replay experience. For example, the file path param -// 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 - } -} - // 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...) @@ -257,83 +192,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) @@ -756,7 +614,7 @@ func (pars Params) findParam(name string) (*Param, error) { // Colorize renders the full parameter list for the {{.Params}} tag. // Each entry is formatted as: key value, with the key in -// amber, the seperator dim, and the value semantically coloured. +// amber, the separator dim, and the value semantically coloured. func (pars Params) Colorize() string { if len(pars) == 0 { return "" @@ -783,50 +641,3 @@ func (pars Params) Colorize() string { return b.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 { - 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: - return colorizer.Span(colorizer.Yellow, p.String()) - - case params.Bool: - b, ok := p.Value.(bool) - if !ok { - return colorizer.Span(colorizer.Coral, p.String()) - } - if b { - return colorizer.Span(colorizer.Green, p.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()) - - case params.Port: - return colorizer.Span(colorizer.Cyan, p.String()) - - case params.PID, params.TID: - return colorizer.Span(colorizer.Green, p.String()) - - default: - return colorizer.Span(colorizer.White, p.String()) - } -} diff --git a/pkg/event/param_linux.go b/pkg/event/param_linux.go new file mode 100644 index 000000000..9cee4cad9 --- /dev/null +++ b/pkg/event/param_linux.go @@ -0,0 +1,221 @@ +//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 ( + "fmt" + "net" + "strconv" + "strings" + "time" + + "github.com/rabbitstack/fibratus/pkg/event/params" + "github.com/rabbitstack/fibratus/pkg/util/colorizer" + "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} +} + +func (p *Param) String() string { + if p.Value == nil { + return "" + } + switch p.Type { + case params.String, params.Path: + return p.Value.(string) + 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 strconv.FormatUint(uint64(p.Value.(uint32)), 10) + 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)) + default: + return fmt.Sprintf("%v", p.Value) + } +} + +func (p Param) CaptureType() params.Type { + return p.Type +} + +// 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 { + switch p.Type { + case params.String: + return colorizer.Span(colorizer.White, p.String()) + case params.Status: + if p.String() == "0" { + return colorizer.Span(colorizer.Green, p.String()) + } + return colorizer.Span(colorizer.Red, p.String()) + case params.Address: + return colorizer.SpanDim(colorizer.Span(colorizer.Gray, "0x"+p.String())) + case params.Int8, params.Int16, params.Int32, params.Int64, + params.Uint8, params.Uint16, params.Uint32, params.Uint64, + params.Float, params.Double: + return colorizer.Span(colorizer.Yellow, p.String()) + case params.Bool: + b, ok := p.Value.(bool) + if !ok { + return colorizer.Span(colorizer.Coral, p.String()) + } + if b { + return colorizer.Span(colorizer.Green, p.String()) + } + return colorizer.Span(colorizer.Coral, p.String()) + case params.IPv4, params.IPv6: + return colorizer.Span(colorizer.Blue, p.String()) + case params.Port: + return colorizer.Span(colorizer.Cyan, p.String()) + case params.PID, params.TID: + return colorizer.Span(colorizer.Green, p.String()) + default: + return colorizer.Span(colorizer.White, p.String()) + } +} + +// 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() (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 +} 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 7d718eb0e..b5ee734f7 100644 --- a/pkg/event/param_windows.go +++ b/pkg/event/param_windows.go @@ -30,8 +30,10 @@ import ( "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" @@ -39,7 +41,6 @@ import ( "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, @@ -63,7 +64,6 @@ func NewParam(name string, typ params.Type, value params.Value, options ...Param 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 "" @@ -164,19 +164,136 @@ func (p Param) String() string { } case params.Binary: return string(p.Value.([]byte)) + default: + return fmt.Sprintf("%v", p.Value) + } +} + +// CaptureType returns the event type saved inside the capture file. +// Captures usually override the type of the parameter to provide +// consistent replay experience. For example, the file path param +// 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 + } +} + +// 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.MemProtect: + if etype == VirtualAlloc || etype == VirtualFree { + flags = MemProtectionFlags + } else { + flags = ViewProtectionFlags + } } - 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) } -// 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. +// 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 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 +304,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 +322,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.Data1 { case RegistryEventGUID.Data1: @@ -254,3 +364,40 @@ func (e *Event) decodeParams(r *etw.EventRecord) { } } } + +// 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 { + switch p.Type { + case params.UnicodeString, params.AnsiString, params.SID: + return colorizer.Span(colorizer.White, p.String()) + case params.Status: + if p.String() == ntstatus.Success { + return colorizer.Span(colorizer.Green, p.String()) + } + return colorizer.Span(colorizer.Red, p.String()) + case params.Address: + return colorizer.SpanDim(colorizer.Span(colorizer.Gray, "0x"+p.String())) + case params.Int8, params.Int16, params.Int32, params.Int64, + params.Uint8, params.Uint16, params.Uint32, params.Uint64, + params.Float, params.Double: + return colorizer.Span(colorizer.Yellow, p.String()) + case params.Bool: + b, ok := p.Value.(bool) + if !ok { + return colorizer.Span(colorizer.Coral, p.String()) + } + if b { + return colorizer.Span(colorizer.Green, p.String()) + } + return colorizer.Span(colorizer.Coral, p.String()) + case params.IPv4, params.IPv6: + return colorizer.Span(colorizer.Blue, p.String()) + case params.Port: + return colorizer.Span(colorizer.Cyan, p.String()) + case params.PID, params.TID: + return colorizer.Span(colorizer.Green, p.String()) + default: + return colorizer.Span(colorizer.White, p.String()) + } +} diff --git a/pkg/event/params/params_windows.go b/pkg/event/params/names.go similarity index 55% rename from pkg/event/params/params_windows.go rename to pkg/event/params/names.go index edc02ca49..054c7d4a8 100644 --- a/pkg/event/params/params_windows.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. @@ -250,9 +147,4 @@ const ( 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" ) diff --git a/pkg/event/params/names_linux.go b/pkg/event/params/names_linux.go new file mode 100644 index 000000000..ebb52580a --- /dev/null +++ b/pkg/event/params/names_linux.go @@ -0,0 +1,72 @@ +//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" + // SyscallID is the raw architecture-specific syscall number. + SyscallID = "syscall_id" + // Retval is the syscall return value. + Retval = "retval" + // StartBootTime is the process start time measured from system boot, in nanoseconds. + StartBootTime = "start_boot_time" + // DirFD is a directory file descriptor, including AT_FDCWD. + DirFD = "dirfd" + // NewDirFD is the destination directory file descriptor for renameat. + NewDirFD = "new_dirfd" + // FileNewPath is the destination path of a rename. + FileNewPath = "file_new_path" + // FileFlags is the raw openat, unlinkat, or renameat2 flags bitmask. + FileFlags = "file_flags" + // FileMode is the file creation mode supplied to openat. + FileMode = "file_mode" + // FD is a file descriptor. + FD = "fd" + // NewFD is the connected file descriptor returned by accept. + NewFD = "new_fd" + // SockFamily is the socket address family (AF_INET, AF_INET6, AF_UNIX). + SockFamily = "sock_family" + // SockFlags is the flags bitmask supplied to accept4. + SockFlags = "sock_flags" + // SockPath is the filesystem path of an AF_UNIX socket. + SockPath = "sock_path" + // MmapFlags is the raw mmap flags bitmask. + MmapFlags = "mmap_flags" + // MmapOffset is the file offset of a memory mapping. + MmapOffset = "mmap_offset" + // Signal is a POSIX signal number. + Signal = "signal" + // PtraceRequest is the ptrace request code. + PtraceRequest = "ptrace_request" + // PtraceAddr is the ptrace address argument. + PtraceAddr = "ptrace_addr" + // PtraceData is the ptrace data argument. + PtraceData = "ptrace_data" + // PrctlOption is the prctl option code. + PrctlOption = "prctl_option" + // Truncated is a bitmask of truncated variable-length fields. + Truncated = "truncated" +) diff --git a/pkg/event/params/names_windows.go b/pkg/event/params/names_windows.go new file mode 100644 index 000000000..8a70e270d --- /dev/null +++ b/pkg/event/params/names_windows.go @@ -0,0 +1,122 @@ +/* + * 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 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 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" + // 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" +) diff --git a/pkg/event/params/param_types.go b/pkg/event/params/param_types.go new file mode 100644 index 000000000..55e546d64 --- /dev/null +++ b/pkg/event/params/param_types.go @@ -0,0 +1,83 @@ +/* + * 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 an event parameter type. +type Type uint16 + +const ( + // 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.go b/pkg/event/params/types.go index e492cb3e6..02c25a14e 100644 --- a/pkg/event/params/types.go +++ b/pkg/event/params/types.go @@ -24,4 +24,4 @@ const ( ) // Value defines the container for parameter values -type Value interface{} +type Value any diff --git a/pkg/event/params/types_linux.go b/pkg/event/params/types_linux.go new file mode 100644 index 000000000..49fe49245 --- /dev/null +++ b/pkg/event/params/types_linux.go @@ -0,0 +1,62 @@ +//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 +) + +// String returns the type name. +func (t Type) String() string { + switch t { + case String: + return "string" + 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 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/params/types_windows.go b/pkg/event/params/types_windows.go index aec8c363d..c8e8c5846 100644 --- a/pkg/event/params/types_windows.go +++ b/pkg/event/params/types_windows.go @@ -18,96 +18,40 @@ 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 + // UnicodeString is a UTF-16LE string. + UnicodeString Type = 1 + // 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 + // String is the future generic string type. + String Type = 38 ) -// String return the type string representation. +// String returns the type name. func (t Type) String() string { switch t { case UnicodeString: return "unicode" case AnsiString: return "ansi" + case String: + return "string" + case SID, WbemSID: + return "sid" case Int8: return "int8" case Uint8: @@ -124,8 +68,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/queue.go b/pkg/event/queue.go index f76460ca1..35d422795 100644 --- a/pkg/event/queue.go +++ b/pkg/event/queue.go @@ -40,40 +40,15 @@ type Listener interface { CanEnqueue() bool } -// Queue is the channel-backed data structure for +// queue is the channel-backed data structure for // pushing captured events and invoking listeners. -type Queue struct { +type queue struct { q chan *Event listeners []Listener - decorator *StackwalkDecorator stackEnrichment bool enqueueAlways bool } -// NewQueue constructs a new queue with the given channel size. -func NewQueue(size int, stackEnrichment bool, enqueueAlways bool) *Queue { - q := &Queue{ - q: make(chan *Event, size), - listeners: make([]Listener, 0), - stackEnrichment: stackEnrichment, - enqueueAlways: enqueueAlways, - } - q.decorator = NewStackwalkDecorator(q) - return q -} - -// NewQueueWithChannel constructs a new queue with a custom channel. -func NewQueueWithChannel(ch chan *Event, stackEnrichment bool, enqueueAlways bool) *Queue { - q := &Queue{ - q: ch, - listeners: make([]Listener, 0), - stackEnrichment: stackEnrichment, - enqueueAlways: enqueueAlways, - } - q.decorator = NewStackwalkDecorator(q) - return q -} - // RegisterListener registers a new queue event listener. The listener // is invoked before the event is pushed to the queue. func (q *Queue) RegisterListener(listener Listener) { @@ -83,48 +58,6 @@ func (q *Queue) RegisterListener(listener Listener) { // Events returns the channel with all queued events. func (q *Queue) Events() <-chan *Event { return q.q } -// Close closes the queue disposing allocated resources. -func (q *Queue) Close() { q.decorator.Stop() } - -// Push pushes a new event to the channel. Prior to -// sending the event to the channel, all registered -// listeners are invoked. The event is sent to the -// channel if one of the listeners agrees so and no -// errors are thrown. If the event depends on the state -// of subsequent events, then we store it in the backlog -// cache. The event is fetched from the backlog cache if -// the matching event arrives, i.e. that backlog key holds -// the value that was used to index the delayed event in the -// backlog. -// It is also the responsibility of the event queue to perform -// callstack enrichment if enabled. We first -// check if the current event is eligible for stack -// enrichment. If such condition is given, the event -// is pushed into callstack decorator FIFO queue. -// The stack return addresses are stored inside StackWalk -// event which is published after the acting event. -// Then, the originating event is popped from the queue, -// 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.WaitStack() { - 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 - } - return q.push(e) -} - func (q *Queue) push(e *Event) error { var enqueue bool if q.enqueueAlways { diff --git a/pkg/event/queue_linux.go b/pkg/event/queue_linux.go new file mode 100644 index 000000000..f0c91ef99 --- /dev/null +++ b/pkg/event/queue_linux.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 event + +type Queue struct { + queue +} + +// NewQueue constructs a new queue with the given channel size. +func NewQueue(size int, stackEnrichment bool, enqueueAlways bool) *Queue { + return &Queue{ + queue: queue{ + q: make(chan *Event, size), + listeners: make([]Listener, 0), + stackEnrichment: stackEnrichment, + enqueueAlways: enqueueAlways, + }, + } +} + +// NewQueueWithChannel constructs a new queue with a custom channel. +func NewQueueWithChannel(ch chan *Event, stackEnrichment bool, enqueueAlways bool) *Queue { + return &Queue{ + queue: queue{ + q: ch, + listeners: make([]Listener, 0), + stackEnrichment: stackEnrichment, + enqueueAlways: enqueueAlways, + }, + } +} + +func (q *Queue) Push(e *Event) error { + return q.push(e) +} + +func (q *Queue) Close() {} diff --git a/pkg/event/queue_linux_test.go b/pkg/event/queue_linux_test.go new file mode 100644 index 000000000..cebd5780d --- /dev/null +++ b/pkg/event/queue_linux_test.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 event + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +func TestQueuePush(t *testing.T) { + queue := NewQueue(1, false, false) + t.Cleanup(queue.Close) + + 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..24594c9f1 --- /dev/null +++ b/pkg/event/queue_windows.go @@ -0,0 +1,100 @@ +/* + * 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 Queue struct { + queue + decorator *StackwalkDecorator +} + +// NewQueue constructs a new queue with the given channel size. +func NewQueue(size int, stackEnrichment bool, enqueueAlways bool) *Queue { + q := &Queue{ + queue: queue{ + q: make(chan *Event, size), + listeners: make([]Listener, 0), + stackEnrichment: stackEnrichment, + enqueueAlways: enqueueAlways, + }, + } + + q.decorator = NewStackwalkDecorator(q) + + return q +} + +// NewQueueWithChannel constructs a new queue with a custom channel. +func NewQueueWithChannel(ch chan *Event, stackEnrichment bool, enqueueAlways bool) *Queue { + q := &Queue{ + queue: queue{ + q: ch, + listeners: make([]Listener, 0), + stackEnrichment: stackEnrichment, + enqueueAlways: enqueueAlways, + }, + } + + q.decorator = NewStackwalkDecorator(q) + + return q +} + +// Close closes the queue disposing allocated resources. +func (q *Queue) Close() { + q.decorator.Stop() +} + +// Push pushes a new event to the channel. Prior to +// sending the event to the channel, all registered +// listeners are invoked. The event is sent to the +// channel if one of the listeners agrees so and no +// errors are thrown. If the event depends on the state +// of subsequent events, then we store it in the backlog +// cache. The event is fetched from the backlog cache if +// the matching event arrives, i.e. that backlog key holds +// the value that was used to index the delayed event in the +// backlog. +// It is also the responsibility of the event queue to perform +// callstack enrichment if enabled. We first +// check if the current event is eligible for stack +// enrichment. If such condition is given, the event +// is pushed into callstack decorator FIFO queue. +// The stack return addresses are stored inside StackWalk +// event which is published after the acting event. +// Then, the originating event is popped from the queue, +// 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.WaitStack() { + 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 + } + return q.push(e) +} diff --git a/pkg/event/queue_test.go b/pkg/event/queue_windows_test.go similarity index 100% rename from pkg/event/queue_test.go rename to pkg/event/queue_windows_test.go diff --git a/pkg/event/sequencer_linux.go b/pkg/event/sequencer_linux.go new file mode 100644 index 000000000..33ea66a38 --- /dev/null +++ b/pkg/event/sequencer_linux.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 event + +import "sync/atomic" + +// Sequencer increments the event sequence number. +type Sequencer struct { + seq uint64 +} + +// NewSequencer creates an in-memory event sequencer. +func NewSequencer() *Sequencer { + return &Sequencer{} +} + +// Increment increments the sequence number atomically. +func (s *Sequencer) Increment() { + atomic.AddUint64(&s.seq, 1) +} + +// Get returns the current sequence number. +func (s *Sequencer) Get() uint64 { + return atomic.LoadUint64(&s.seq) +} + +// Reset sets the sequence number to zero. +func (s *Sequencer) Reset() error { + atomic.StoreUint64(&s.seq, 0) + return nil +} + +// Close is a no-op on Linux. +func (s *Sequencer) Close() error { return nil } + +// Shutdown closes the sequencer. +func (s *Sequencer) Shutdown() error { return s.Close() } diff --git a/pkg/event/sequencer_linux_test.go b/pkg/event/sequencer_linux_test.go new file mode 100644 index 000000000..1fec3500e --- /dev/null +++ b/pkg/event/sequencer_linux_test.go @@ -0,0 +1,43 @@ +//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" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestSequencer(t *testing.T) { + sequencer := NewSequencer() + defer sequencer.Close() + + assert.Equal(t, uint64(0), sequencer.Get()) + for i := 0; i < 10; i++ { + sequencer.Increment() + } + assert.Equal(t, uint64(10), sequencer.Get()) + + require.NoError(t, sequencer.Reset()) + assert.Equal(t, uint64(0), sequencer.Get()) + require.NoError(t, sequencer.Shutdown()) +} diff --git a/pkg/event/stackwalk.go b/pkg/event/stackwalk_windows.go similarity index 100% rename from pkg/event/stackwalk.go rename to pkg/event/stackwalk_windows.go diff --git a/pkg/event/stackwalk_test.go b/pkg/event/stackwalk_windows_test.go similarity index 100% rename from pkg/event/stackwalk_test.go rename to pkg/event/stackwalk_windows_test.go diff --git a/pkg/event/types_linux.go b/pkg/event/types_linux.go new file mode 100644 index 000000000..0a05bae4a --- /dev/null +++ b/pkg/event/types_linux.go @@ -0,0 +1,67 @@ +//go:build linux + +/* + * Copyright 2026 by Mostafa Moradian + * 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" +) + +// Source identifies a Linux event source. +type Source uint8 + +const ( + // RawSyscallTracepoint identifies events from the raw syscall tracepoint. + RawSyscallTracepoint Source = iota +) + +// Type identifies a Linux event type. +type Type uint16 + +const ( + Unknown Type = iota + Execve + Exit + Clone + Openat + Unlink + Rename + Connect + Accept + Mmap + ProcessVMRead + ProcessVMWrite + Kill + Ptrace + Prctl + MaxEvent +) + +// String returns the event type string representation. +func (t Type) String() string { return table[t].Name } + +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/filter/accessor.go b/pkg/filter/accessor.go index ea14a98f8..e81644511 100644 --- a/pkg/filter/accessor.go +++ b/pkg/filter/accessor.go @@ -24,7 +24,6 @@ import ( "reflect" "time" - "github.com/rabbitstack/fibratus/internal/evasion" "github.com/rabbitstack/fibratus/pkg/event" "github.com/rabbitstack/fibratus/pkg/event/params" "github.com/rabbitstack/fibratus/pkg/filter/fields" @@ -37,7 +36,7 @@ var ( // Accessor dictates the behaviour of the field accessors. One of the main responsibilities of the accessor is // to extract the underlying parameter for the field given in the filter expression. It can also produce a value -// from the non-params constructs such as process' state or PE metadata. +// from the non-params constructs such as process' state. type Accessor interface { // Get fetches the parameter value for the specified filter field. Get(f Field, evt *event.Event) (params.Value, error) @@ -66,7 +65,7 @@ func newEventAccessor() Accessor { const timeFmt = "15:04:05" const dateFmt = "2006-01-02" -func (*evtAccessor) Get(f Field, evt *event.Event) (params.Value, error) { +func (*evtAccessor) get(f Field, evt *event.Event) (params.Value, error) { switch f.Name { case fields.EvtSeq, fields.KevtSeq: return evt.Seq, nil @@ -138,12 +137,7 @@ func (*evtAccessor) Get(f Field, evt *event.Event) (params.Value, error) { default: return evt.GetParamAsString(name), nil } - case fields.EvtIsDirectSyscall: - return evt.Evasions&uint32(evasion.DirectSyscall) != 0, nil - case fields.EvtIsIndirectSyscall: - return evt.Evasions&uint32(evasion.IndirectSyscall) != 0, nil } - return nil, nil } @@ -152,75 +146,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 - removePEAccessor = true - removeMemAccessor = true - removeDNSAccessor = 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.IsMemField(): - removeMemAccessor = false - case field.Name.IsDNSField(): - removeDNSAccessor = 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 removePEAccessor { - f.removeAccessor(&peAccessor{}) - } - if removeMemAccessor { - f.removeAccessor(&memAccessor{}) - } - if removeDNSAccessor { - f.removeAccessor(&dnsAccessor{}) - } - + 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..ae137d04f --- /dev/null +++ b/pkg/filter/accessor_linux.go @@ -0,0 +1,392 @@ +//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 filter + +import ( + "path/filepath" + "strings" + + "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" + pstypes "github.com/rabbitstack/fibratus/pkg/ps/types" +) + +// GetAccessors returns the accessors available on Linux. +func GetAccessors() []Accessor { + return []Accessor{ + newEventAccessor(), + newPSAccessor(nil), + newFileAccessor(), + newNetworkAccessor(), + newMemAccessor(), + newThreadAccessor(), + } +} + +func (e *evtAccessor) Get(f Field, evt *event.Event) (params.Value, error) { + v, err := e.get(f, evt) + if v != nil { + return v, err + } + + switch f.Name { + case fields.EvtRetval: + return evt.Params.GetInt64(params.Retval) + case fields.EvtSyscallID: + return evt.Params.GetUint32(params.SyscallID) + } + + return nil, err +} + +func getParentPs(e *event.Event) *pstypes.PS { + if e.PS == nil { + return nil + } + return e.PS.Parent +} + +type psAccessor struct { + psnap ps.Snapshotter +} + +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.Snapshotter) 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.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.PsUID: + if e.PS != nil { + return e.PS.UID, nil + } + return e.Params.GetUint32(params.UID) + case fields.PsGID: + if e.PS != nil { + return e.PS.GID, nil + } + return e.Params.GetUint32(params.GID) + case fields.PsUUID: + if e.PS == nil { + return nil, ErrPsNil + } + return e.PS.UUID(), nil + case fields.PsEnvs: + if e.PS == nil { + return nil, ErrPsNil + } + if f.Arg != "" { + if v, ok := e.PS.Envs[f.Arg]; ok { + return v, nil + } + for k, v := range e.PS.Envs { + if strings.HasPrefix(k, f.Arg) { + return v, nil + } + } + return "", nil + } + envs := make([]string, 0, len(e.PS.Envs)) + for k, v := range e.PS.Envs { + envs = append(envs, k+":"+v) + } + return envs, nil + case fields.PsParentPid: + parent := getParentPs(e) + if parent == nil { + return nil, ErrPsNil + } + return parent.PID, nil + case fields.PsParentName: + parent := getParentPs(e) + if parent == nil { + return nil, ErrPsNil + } + return parent.Name, nil + case fields.PsParentCmdline: + parent := getParentPs(e) + if parent == nil { + return nil, ErrPsNil + } + return parent.Cmdline, nil + case fields.PsParentExe: + parent := getParentPs(e) + if parent == nil { + return nil, ErrPsNil + } + return parent.Exe, nil + case fields.PsParentArgs: + parent := getParentPs(e) + if parent == nil { + return nil, ErrPsNil + } + return parent.Args, nil + case fields.PsParentCwd: + parent := getParentPs(e) + if parent == nil { + return nil, ErrPsNil + } + return parent.Cwd, nil + case fields.PsParentUsername: + parent := getParentPs(e) + if parent == nil { + return nil, ErrPsNil + } + return parent.Username, nil + case fields.PsParentUUID: + parent := getParentPs(e) + if parent == nil { + return nil, ErrPsNil + } + return parent.UUID(), nil + case fields.PsParentEnvs: + parent := getParentPs(e) + if parent == nil { + return nil, ErrPsNil + } + envs := make([]string, 0, len(parent.Envs)) + for k, v := range parent.Envs { + envs = append(envs, k+":"+v) + } + return envs, nil + case fields.PsSignal: + sig, err := e.Params.GetInt32(params.Signal) + if err != nil { + return nil, err + } + return int64(sig), nil + case fields.PsTargetPID: + return e.Params.GetInt64(params.TargetProcessID) + case fields.PsPtraceRequest: + return e.Params.GetInt64(params.PtraceRequest) + case fields.PsPrctlOption: + return e.Params.GetInt64(params.PrctlOption) + case fields.PsCloneFlags: + return e.Params.GetUint64(params.CloneFlags) + default: + return nil, nil + } +} + +type fileAccessor struct{} + +func (fileAccessor) SetFields([]Field) {} +func (fileAccessor) SetSegments([]fields.Segment) {} +func (fileAccessor) IsFieldAccessible(e *event.Event) bool { return e.Category() == event.File } +func newFileAccessor() Accessor { return &fileAccessor{} } + +func (*fileAccessor) Get(f Field, e *event.Event) (params.Value, error) { + switch f.Name { + case fields.FilePath: + return e.GetParamAsString(params.FilePath), nil + case fields.FilePathStem: + return pathStem(e.GetParamAsString(params.FilePath)), nil + case fields.FileName: + return filepath.Base(e.GetParamAsString(params.FilePath)), nil + case fields.FileExtension: + return filepath.Ext(e.GetParamAsString(params.FilePath)), nil + case fields.FilePathTarget: + return e.GetParamAsString(params.FileNewPath), nil + case fields.FileDirFD: + return e.Params.GetInt64(params.DirFD) + case fields.FileFD: + return e.Params.GetInt64(params.FD) + case fields.FileFlags: + return e.Params.GetUint64(params.FileFlags) + case fields.FileMode: + return e.Params.GetUint64(params.FileMode) + default: + return nil, nil + } +} + +type networkAccessor struct{} + +func (networkAccessor) SetFields([]Field) {} +func (networkAccessor) SetSegments([]fields.Segment) {} +func (networkAccessor) IsFieldAccessible(e *event.Event) bool { return e.Category() == event.Network } +func newNetworkAccessor() Accessor { return &networkAccessor{} } + +func (*networkAccessor) Get(f Field, e *event.Event) (params.Value, error) { + switch f.Name { + case fields.NetDIP: + return e.Params.GetIP(params.NetDIP) + case fields.NetSIP: + return e.Params.GetIP(params.NetSIP) + case fields.NetDport: + return e.Params.GetUint16(params.NetDport) + case fields.NetSport: + return e.Params.GetUint16(params.NetSport) + case fields.NetFamily: + return e.Params.GetUint16(params.SockFamily) + case fields.NetUnixPath: + return e.GetParamAsString(params.SockPath), nil + case fields.NetFD: + return e.Params.GetInt64(params.FD) + default: + return nil, nil + } +} + +type memAccessor struct{} + +func (memAccessor) SetFields([]Field) {} +func (memAccessor) SetSegments([]fields.Segment) {} +func (memAccessor) IsFieldAccessible(e *event.Event) bool { return e.Category() == event.Memory } +func newMemAccessor() Accessor { return &memAccessor{} } + +func (*memAccessor) Get(f Field, e *event.Event) (params.Value, error) { + switch f.Name { + case fields.MemBaseAddress: + return e.Params.GetUint64(params.MemBaseAddress) + case fields.MemRegionSize: + return e.Params.GetUint64(params.MemRegionSize) + case fields.MemProtection: + return e.Params.GetUint32(params.MemProtect) + case fields.MemMmapFlags: + return e.Params.GetUint64(params.MmapFlags) + case fields.MemMmapFD: + return e.Params.GetInt64(params.FD) + case fields.MemMmapOffset: + return e.Params.GetUint64(params.MmapOffset) + case fields.MemTargetPID: + return e.Params.GetInt64(params.TargetProcessID) + default: + return nil, nil + } +} + +type threadAccessor struct{} + +func (threadAccessor) SetFields([]Field) {} +func (threadAccessor) SetSegments([]fields.Segment) {} +func (threadAccessor) IsFieldAccessible(e *event.Event) bool { + return e.IsCreateThread() +} +func newThreadAccessor() Accessor { return &threadAccessor{} } + +func (*threadAccessor) Get(f Field, e *event.Event) (params.Value, error) { + switch f.Name { + case fields.ThreadTID: + return e.Tid, nil + case fields.ThreadPID: + return e.PID, nil + default: + return nil, nil + } +} + +func pathStem(p string) string { + n := strings.LastIndexByte(p, '.') + if n == -1 { + return p + } + return p[:n] +} + +func (f *filter) pruneUnusedAccessors() { + removeEvtAccessor := true + removePsAccessor := true + removeFileAccessor := true + removeNetworkAccessor := true + removeMemAccessor := true + removeThreadAccessor := true + + for _, field := range f.fields { + switch { + case field.Name.IsEvtField() || field.Name.IsKevtField(): + removeEvtAccessor = false + case field.Name.IsPsField(): + removePsAccessor = false + case field.Name.IsFileField(): + removeFileAccessor = false + case field.Name.IsNetworkField(): + removeNetworkAccessor = false + case field.Name.IsMemField(): + removeMemAccessor = false + case field.Name.IsThreadField(): + removeThreadAccessor = false + } + } + + if removeEvtAccessor { + f.removeAccessor(&evtAccessor{}) + } + if removePsAccessor { + f.removeAccessor(&psAccessor{}) + } + if removeFileAccessor { + f.removeAccessor(&fileAccessor{}) + } + if removeNetworkAccessor { + f.removeAccessor(&networkAccessor{}) + } + if removeMemAccessor { + f.removeAccessor(&memAccessor{}) + } + if removeThreadAccessor { + f.removeAccessor(&threadAccessor{}) + } +} diff --git a/pkg/filter/accessor_windows.go b/pkg/filter/accessor_windows.go index e39cd59ef..9e8b7c738 100644 --- a/pkg/filter/accessor_windows.go +++ b/pkg/filter/accessor_windows.go @@ -26,6 +26,7 @@ import ( "strings" "time" + "github.com/rabbitstack/fibratus/internal/evasion" "github.com/rabbitstack/fibratus/pkg/callstack" "github.com/rabbitstack/fibratus/pkg/fs" "github.com/rabbitstack/fibratus/pkg/network" @@ -68,6 +69,22 @@ func getParentPs(e *event.Event) *pstypes.PS { return e.PS.Parent } +func (e *evtAccessor) Get(f Field, evt *event.Event) (params.Value, error) { + v, err := e.get(f, evt) + if v != nil { + return v, err + } + + switch f.Name { + case fields.EvtIsDirectSyscall: + return evt.Evasions&uint32(evasion.DirectSyscall) != 0, nil + case fields.EvtIsIndirectSyscall: + return evt.Evasions&uint32(evasion.IndirectSyscall) != 0, nil + } + + return nil, err +} + // psAccessor extracts process's state or event specific values. type psAccessor struct { psnap psnap.Snapshotter @@ -1261,3 +1278,74 @@ func (*dnsAccessor) 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 + removePEAccessor = true + removeMemAccessor = true + removeDNSAccessor = 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.IsMemField(): + removeMemAccessor = false + case field.Name.IsDNSField(): + removeDNSAccessor = 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 removePEAccessor { + f.removeAccessor(&peAccessor{}) + } + if removeMemAccessor { + f.removeAccessor(&memAccessor{}) + } + if removeDNSAccessor { + f.removeAccessor(&dnsAccessor{}) + } +} diff --git a/pkg/filter/accessor_windows_test.go b/pkg/filter/accessor_windows_test.go index 0035e7f52..822ddb7cb 100644 --- a/pkg/filter/accessor_windows_test.go +++ b/pkg/filter/accessor_windows_test.go @@ -71,6 +71,17 @@ func TestNarrowAccessors(t *testing.T) { assert.Len(t, pea.fields, 2) } +func eventWithCallstack(typ event.Type) *event.Event { + e := &event.Event{Type: typ} + 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 @@ -104,22 +115,22 @@ func TestIsFieldAccessible(t *testing.T) { }, { newThreadAccessor(), - &event.Event{Type: event.CreateProcess, Callstack: []callstack.Frame{{Addr: 0x7ffb5c1d0396, Offset: 0x61, Symbol: "CreateProcessW", Module: "C:\\WINDOWS\\System32\\KERNELBASE.dll"}}}, + eventWithCallstack(event.CreateProcess), true, }, { newThreadAccessor(), - &event.Event{Type: event.RegSetValue, Callstack: []callstack.Frame{{Addr: 0x7ffb5c1d0396, Offset: 0x61, Symbol: "CreateProcessW", Module: "C:\\WINDOWS\\System32\\KERNELBASE.dll"}}}, + eventWithCallstack(event.RegSetValue), true, }, { newRegistryAccessor(), - &event.Event{Type: event.RegSetValue, Callstack: []callstack.Frame{{Addr: 0x7ffb5c1d0396, Offset: 0x61, Symbol: "CreateProcessW", Module: "C:\\WINDOWS\\System32\\KERNELBASE.dll"}}}, + eventWithCallstack(event.RegSetValue), true, }, { newNetworkAccessor(), - &event.Event{Type: event.RegSetValue, Callstack: []callstack.Frame{{Addr: 0x7ffb5c1d0396, Offset: 0x61, Symbol: "CreateProcessW", Module: "C:\\WINDOWS\\System32\\KERNELBASE.dll"}}}, + eventWithCallstack(event.RegSetValue), false, }, { diff --git a/pkg/filter/approver.go b/pkg/filter/approver.go new file mode 100644 index 000000000..25a3c3a9d --- /dev/null +++ b/pkg/filter/approver.go @@ -0,0 +1,646 @@ +/* + * 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 + +import ( + "slices" + "strconv" + "strings" + + "github.com/rabbitstack/fibratus/pkg/event" + "github.com/rabbitstack/fibratus/pkg/filter/fields" + "github.com/rabbitstack/fibratus/pkg/filter/ql" +) + +// ApproverProvider is an optional filter capability that exposes a +// conservative, kernel-safe extraction of positive predicates. Filters +// that do not implement it are treated as unextractable, which forces +// default-allow for every event type they could match. +type ApproverProvider interface { + ApproverExtraction() Extraction +} + +// Extraction is the conservative predicate set taken from one compiled +// filter. Unsupported is set when the AST contains a shape that cannot +// be proven as a superset of matches (OR, NOT, inequality, regex, range, +// function, bound field, or sequence). +type Extraction struct { + Unsupported bool + Types []event.Type + TypesScoped bool + PIDs []uint64 + FileExact []string + FilePrefix []string + Ports []uint16 +} + +// TypePolicy is the in-kernel prefilter for one event type. DefaultAllow +// means userspace must see every event of that type. Otherwise an event +// must satisfy every required field, matching the union of allowed values. +type TypePolicy struct { + DefaultAllow bool + RequirePID bool + RequireFilename bool + RequirePort bool + PIDs []uint64 + FileExact []string + FilePrefix []string + Ports []uint16 +} + +// ApproverPlan is a platform-neutral description of per-type prefilters. +// It is derived from compiled filters and is not stored on RulesCompileResult, +// which remains a usage summary. +type ApproverPlan struct { + policies map[event.Type]TypePolicy +} + +// Sample is the subset of event fields the in-kernel approver can observe. +type Sample struct { + Type event.Type + PID uint64 + Filename string + Port uint16 + Truncated bool +} + +// AllowAllPlan returns a plan that never drops events. +func AllowAllPlan() *ApproverPlan { + return &ApproverPlan{policies: map[event.Type]TypePolicy{}} +} + +// PlanFromFilter builds a plan from a single compiled filter, typically the CLI +// expression supplied through SetFilter. +func PlanFromFilter(f Filter) *ApproverPlan { + if f == nil { + return AllowAllPlan() + } + return BuildApproverPlan([]Filter{f}) +} + +// BuildApproverPlan unions extractable predicates across filters. A type is +// default-allow when any applicable filter is unextractable, when no filter +// applies, or when the applicable filters do not share a required field. +func BuildApproverPlan(filters []Filter) *ApproverPlan { + plan := AllowAllPlan() + if len(filters) == 0 { + return plan + } + + byType := make(map[event.Type][]Extraction) + blocked := make(map[event.Type]bool) + + for _, f := range filters { + provider, ok := f.(ApproverProvider) + if !ok { + for _, typ := range event.AllTypes() { + blocked[typ] = true + } + continue + } + ex := provider.ApproverExtraction() + types := scopedTypes(ex) + if ex.Unsupported { + for _, typ := range types { + blocked[typ] = true + } + continue + } + for _, typ := range types { + byType[typ] = append(byType[typ], ex) + } + } + + for _, typ := range event.AllTypes() { + if blocked[typ] || len(byType[typ]) == 0 { + plan.policies[typ] = TypePolicy{DefaultAllow: true} + continue + } + plan.policies[typ] = policyFromClauses(byType[typ]) + } + return plan +} + +// Union combines plans by intersecting required fields and unioning their +// allowed values. Any default-allow policy wins, which is the safe direction. +func Union(plans ...*ApproverPlan) *ApproverPlan { + var out *ApproverPlan + for _, p := range plans { + if p == nil { + continue + } + if out == nil { + out = clonePlan(p) + continue + } + for _, typ := range event.AllTypes() { + out.policies[typ] = unionPolicy(out.Policy(typ), p.Policy(typ)) + } + } + if out == nil { + return AllowAllPlan() + } + return out +} + +// Policy returns the prefilter for an event type. Missing types default-allow. +func (p *ApproverPlan) Policy(t event.Type) TypePolicy { + if p == nil || p.policies == nil { + return TypePolicy{DefaultAllow: true} + } + pol, ok := p.policies[t] + if !ok { + return TypePolicy{DefaultAllow: true} + } + return pol +} + +// Allows reports whether the kernel prefilter would keep the sample. A true +// userspace match must always produce true here; false positives are allowed. +func (p *ApproverPlan) Allows(s Sample) bool { + if AlwaysAllowed(s.Type) { + return true + } + pol := p.Policy(s.Type) + if pol.DefaultAllow { + return true + } + if pol.RequirePID && !slices.Contains(pol.PIDs, s.PID) { + return false + } + if pol.RequireFilename && !s.Truncated && !matchFilename(pol, s.Filename) { + return false + } + if pol.RequirePort && !slices.Contains(pol.Ports, s.Port) { + return false + } + return true +} + +var _ ApproverProvider = (*filter)(nil) + +func (f *filter) ApproverExtraction() Extraction { + if f.seq != nil { + // Sequence matching is stateful: an early stage has to reach userspace + // for a later one to ever fire, so no stage can be prefiltered. Scope + // the block to the event names and categories in the filter's string + // fields, which is the same set rules.Engine indexes the sequence by, + // so the approver and the engine cannot disagree about which types can + // reach the rule. + ex := Extraction{Unsupported: true, TypesScoped: true} + ex.Types = typesFromStringFields(f.stringFields) + return ex + } + return extractFromExpr(f.expr) +} + +// typesFromStringFields mirrors the event name and category indexing performed +// by rules.Engine.Compile. +func typesFromStringFields(stringFields map[fields.Field][]string) []event.Type { + var types []event.Type + for _, name := range stringFields[fields.EvtName] { + typ, ok := event.ParseType(name) + if !ok { + continue + } + types = append(types, typ) + } + for _, name := range stringFields[fields.EvtCategory] { + cat, ok := event.ParseCategory(name) + if !ok { + continue + } + for _, typ := range event.AllTypes() { + info := event.GetTypeInfo(typ) + if info.Category == cat { + types = append(types, typ) + } + } + } + return uniqueTypes(types) +} + +func extractFromExpr(root ql.Node) Extraction { + var ex Extraction + if root == nil { + ex.Unsupported = true + return ex + } + ql.WalkFunc(root, func(n ql.Node) { + switch node := n.(type) { + case *ql.NotExpr, *ql.Function: + ex.Unsupported = true + case *ql.BinaryExpr: + extractBinary(&ex, node) + } + }) + ex.Types = uniqueTypes(ex.Types) + ex.PIDs = uniqueUint64(ex.PIDs) + ex.FileExact = uniqueStrings(ex.FileExact) + ex.FilePrefix = uniqueStrings(ex.FilePrefix) + ex.Ports = uniqueUint16(ex.Ports) + return ex +} + +func extractBinary(ex *Extraction, expr *ql.BinaryExpr) { + switch expr.Op { + case ql.And: + return + case ql.Or: + ex.Unsupported = true + return + } + + lhs, ok := expr.LHS.(*ql.FieldLiteral) + if !ok { + ex.Unsupported = true + return + } + if _, ok := expr.RHS.(*ql.BoundFieldLiteral); ok { + ex.Unsupported = true + return + } + + switch lhs.Field { + case fields.EvtName: + extractEventNames(ex, expr) + case fields.EvtCategory: + extractCategories(ex, expr) + case fields.EvtPID, fields.PsPid: + extractPIDs(ex, expr) + case fields.FilePath: + extractFilenames(ex, expr) + case fields.NetDport: + extractPorts(ex, expr) + default: + // ps.name is deliberately absent. The only process name the kernel can + // read cheaply is the live task comm, while ps.name is snapshot state + // captured at execve. They diverge under prctl(PR_SET_NAME) and when + // the snapshot falls back to an executable basename longer than comm's + // 16 bytes, either of which would drop a matching event. + ex.Unsupported = true + } +} + +func extractEventNames(ex *Extraction, expr *ql.BinaryExpr) { + if expr.Op != ql.Eq && expr.Op != ql.In { + ex.Unsupported = true + return + } + names, ok := rhsStrings(expr.RHS) + if !ok { + ex.Unsupported = true + return + } + ex.TypesScoped = true + for _, name := range names { + typ, ok := event.ParseType(name) + if !ok { + continue + } + ex.Types = append(ex.Types, typ) + } +} + +func extractCategories(ex *Extraction, expr *ql.BinaryExpr) { + if expr.Op != ql.Eq && expr.Op != ql.In { + ex.Unsupported = true + return + } + names, ok := rhsStrings(expr.RHS) + if !ok { + ex.Unsupported = true + return + } + ex.TypesScoped = true + for _, name := range names { + cat, ok := event.ParseCategory(name) + if !ok { + continue + } + for _, typ := range event.AllTypes() { + info := event.GetTypeInfo(typ) + if info.Category == cat { + ex.Types = append(ex.Types, typ) + } + } + } +} + +func extractPIDs(ex *Extraction, expr *ql.BinaryExpr) { + if expr.Op != ql.Eq && expr.Op != ql.In { + ex.Unsupported = true + return + } + nums, ok := rhsUint64(expr.RHS) + if !ok { + ex.Unsupported = true + return + } + ex.PIDs = append(ex.PIDs, nums...) +} + +func extractFilenames(ex *Extraction, expr *ql.BinaryExpr) { + switch expr.Op { + case ql.Eq, ql.In: + names, ok := rhsStrings(expr.RHS) + if !ok { + ex.Unsupported = true + return + } + ex.FileExact = append(ex.FileExact, names...) + case ql.Startswith: + names, ok := rhsStrings(expr.RHS) + if !ok { + ex.Unsupported = true + return + } + for _, name := range names { + if name == "" { + continue + } + ex.FilePrefix = append(ex.FilePrefix, name) + } + case ql.Matches: + names, ok := rhsStrings(expr.RHS) + if !ok { + ex.Unsupported = true + return + } + for _, name := range names { + literal, prefix, ok := globAsPrefix(name) + if !ok { + ex.Unsupported = true + return + } + switch { + case literal != "": + ex.FileExact = append(ex.FileExact, literal) + case prefix != "": + ex.FilePrefix = append(ex.FilePrefix, prefix) + } + } + default: + // imatches stays out: case folding the path in the kernel would have to + // agree with unicode.ToLower on every rune userspace folds. + ex.Unsupported = true + } +} + +func extractPorts(ex *Extraction, expr *ql.BinaryExpr) { + if expr.Op != ql.Eq && expr.Op != ql.In { + ex.Unsupported = true + return + } + nums, ok := rhsUint64(expr.RHS) + if !ok { + ex.Unsupported = true + return + } + for _, n := range nums { + if n > 65535 { + ex.Unsupported = true + return + } + ex.Ports = append(ex.Ports, uint16(n)) + } +} + +// scopedTypes resolves which event types an extraction speaks for. An +// extraction that names no event type at all covers every type, which is right +// for a CLI filter because the source evaluates it against every event. Rules +// are not in that position: rules.Engine discards a rule without an event name +// or category, so the compiler keeps unscoped rules out of the plan entirely +// rather than letting their predicates constrain anything here. +func scopedTypes(ex Extraction) []event.Type { + if len(ex.Types) > 0 { + return uniqueTypes(ex.Types) + } + if ex.TypesScoped { + return nil + } + return event.AllTypes() +} + +func policyFromClauses(clauses []Extraction) TypePolicy { + reqPID, reqFile, reqPort := true, true, true + for _, c := range clauses { + if len(c.PIDs) == 0 { + reqPID = false + } + if len(c.FileExact)+len(c.FilePrefix) == 0 { + reqFile = false + } + if len(c.Ports) == 0 { + reqPort = false + } + } + if !reqPID && !reqFile && !reqPort { + return TypePolicy{DefaultAllow: true} + } + pol := TypePolicy{ + RequirePID: reqPID, + RequireFilename: reqFile, + RequirePort: reqPort, + } + for _, c := range clauses { + if reqPID { + pol.PIDs = append(pol.PIDs, c.PIDs...) + } + if reqFile { + pol.FileExact = append(pol.FileExact, c.FileExact...) + pol.FilePrefix = append(pol.FilePrefix, c.FilePrefix...) + } + if reqPort { + pol.Ports = append(pol.Ports, c.Ports...) + } + } + pol.PIDs = uniqueUint64(pol.PIDs) + pol.FileExact = uniqueStrings(pol.FileExact) + pol.FilePrefix = uniqueStrings(pol.FilePrefix) + pol.Ports = uniqueUint16(pol.Ports) + return pol +} + +func unionPolicy(a, b TypePolicy) TypePolicy { + if a.DefaultAllow || b.DefaultAllow { + return TypePolicy{DefaultAllow: true} + } + reqPID := a.RequirePID && b.RequirePID + reqFile := a.RequireFilename && b.RequireFilename + reqPort := a.RequirePort && b.RequirePort + if !reqPID && !reqFile && !reqPort { + return TypePolicy{DefaultAllow: true} + } + pol := TypePolicy{ + RequirePID: reqPID, + RequireFilename: reqFile, + RequirePort: reqPort, + } + if reqPID { + pol.PIDs = uniqueUint64(append(append([]uint64{}, a.PIDs...), b.PIDs...)) + } + if reqFile { + pol.FileExact = uniqueStrings(append(append([]string{}, a.FileExact...), b.FileExact...)) + pol.FilePrefix = uniqueStrings(append(append([]string{}, a.FilePrefix...), b.FilePrefix...)) + } + if reqPort { + pol.Ports = uniqueUint16(append(append([]uint16{}, a.Ports...), b.Ports...)) + } + return pol +} + +func clonePlan(p *ApproverPlan) *ApproverPlan { + out := AllowAllPlan() + for typ, pol := range p.policies { + out.policies[typ] = pol + } + return out +} + +// globAsPrefix rewrites a matches pattern into the exact or prefix form the +// kernel can already evaluate. There is no in-kernel glob matcher because a +// backtracking one is not verifiable, so only patterns provably equivalent to +// one of those two forms are accepted: +// +// /etc/passwd -> exact, no wildcard at all +// /tmp/* -> prefix, since '*' spans every remaining byte including '/' +// * -> vacuous, matches everything and constrains nothing +// +// A '*' anywhere but the end, or any '?', reports false and leaves the event +// type default-allow. Callers must pass the pattern through collapseStars so +// /tmp/** reaches here as /tmp/*. +func globAsPrefix(pattern string) (literal, prefix string, ok bool) { + pattern = collapseStars(pattern) + if strings.ContainsRune(pattern, '?') { + return "", "", false + } + switch strings.Count(pattern, "*") { + case 0: + return pattern, "", true + case 1: + if !strings.HasSuffix(pattern, "*") { + return "", "", false + } + return "", strings.TrimSuffix(pattern, "*"), true + default: + return "", "", false + } +} + +// collapseStars rewrites runs of '*' as a single '*'. The two are equivalent to +// matchCaseSensitive, which only ever remembers the most recent star position. +func collapseStars(pattern string) string { + if !strings.Contains(pattern, "**") { + return pattern + } + var b strings.Builder + b.Grow(len(pattern)) + var prevStar bool + for i := range len(pattern) { + c := pattern[i] + if c == '*' && prevStar { + continue + } + prevStar = c == '*' + b.WriteByte(c) + } + return b.String() +} + +func matchFilename(pol TypePolicy, path string) bool { + if slices.Contains(pol.FileExact, path) { + return true + } + for _, prefix := range pol.FilePrefix { + if strings.HasPrefix(path, prefix) { + return true + } + } + return false +} + +func rhsStrings(n ql.Node) ([]string, bool) { + switch v := n.(type) { + case *ql.StringLiteral: + return []string{v.Value}, true + case *ql.ListLiteral: + return v.Values, true + } + return nil, false +} + +func rhsUint64(n ql.Node) ([]uint64, bool) { + switch v := n.(type) { + case *ql.IntegerLiteral: + if v.Value < 0 { + return nil, false + } + return []uint64{uint64(v.Value)}, true + case *ql.UnsignedLiteral: + return []uint64{v.Value}, true + case *ql.StringLiteral: + n, err := strconv.ParseUint(v.Value, 10, 64) + if err != nil { + return nil, false + } + return []uint64{n}, true + case *ql.ListLiteral: + out := make([]uint64, 0, len(v.Values)) + for _, s := range v.Values { + n, err := strconv.ParseUint(s, 10, 64) + if err != nil { + return nil, false + } + out = append(out, n) + } + return out, true + } + return nil, false +} + +func uniqueTypes(in []event.Type) []event.Type { + return unique(in, func(a, b event.Type) bool { return a == b }) +} + +func uniqueUint64(in []uint64) []uint64 { + return unique(in, func(a, b uint64) bool { return a == b }) +} + +func uniqueUint16(in []uint16) []uint16 { + return unique(in, func(a, b uint16) bool { return a == b }) +} + +func uniqueStrings(in []string) []string { + return unique(in, func(a, b string) bool { return a == b }) +} + +func unique[T any](in []T, eq func(T, T) bool) []T { + if len(in) == 0 { + return nil + } + out := make([]T, 0, len(in)) + for _, v := range in { + if slices.ContainsFunc(out, func(e T) bool { return eq(e, v) }) { + continue + } + out = append(out, v) + } + return out +} diff --git a/pkg/filter/approver_fuzz_linux_test.go b/pkg/filter/approver_fuzz_linux_test.go new file mode 100644 index 000000000..664bed6da --- /dev/null +++ b/pkg/filter/approver_fuzz_linux_test.go @@ -0,0 +1,120 @@ +//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 filter + +import ( + "testing" + + "github.com/rabbitstack/fibratus/pkg/event" + "github.com/rabbitstack/fibratus/pkg/event/params" + pstypes "github.com/rabbitstack/fibratus/pkg/ps/types" + "github.com/stretchr/testify/require" +) + +// fuzzExprs mixes extractable shapes with shapes that must fall back to +// default-allow, so the property holds across both paths. +var fuzzExprs = []string{ + "evt.name = 'openat' and file.path startswith '/tmp'", + "evt.name = 'openat' and file.path = '/etc/passwd'", + "evt.name = 'openat' and file.path in ('/tmp/a', '/tmp/b') and ps.pid = 42", + "evt.name in ('openat', 'connect') and ps.pid in (1, 42)", + "evt.category = 'file' and file.path startswith '/var'", + "evt.name = 'openat' and file.path matches '/tmp/*'", + "evt.name = 'openat' and file.path matches ('/tmp/*', '/var/tmp/**')", + "evt.name = 'openat' and file.path matches '/etc/passwd'", + "evt.name = 'openat' and file.path matches '/tmp/*/evil'", + "evt.name = 'openat' and file.path matches '*.so'", + "evt.name = 'openat' and file.path matches '*'", + "evt.name = 'openat' and file.path imatches '/TMP/*'", + "evt.name = 'connect' and net.dport in (80, 443)", + "evt.name = 'connect' and net.dport = 443 and ps.pid = 42", + "evt.name = 'kill' and ps.pid = 42", + "evt.name = 'openat' and file.path != '/tmp/x'", + "evt.name = 'openat' and not (file.path = '/tmp/x')", + "evt.name = 'openat' and (ps.pid = 1 or file.path = '/tmp/x')", + "evt.name = 'openat' and ps.name = 'bash'", + "file.path startswith '/tmp'", + "ps.pid = 42", +} + +var fuzzTypes = []event.Type{ + event.Openat, event.Connect, event.Kill, event.Execve, event.Mmap, event.Accept, +} + +func fuzzEvent(typ event.Type, pid uint64, path string, port uint16) *event.Event { + evt := &event.Event{ + Type: typ, + Category: typ.Category(), + Name: typ.String(), + PID: pid, + PS: &pstypes.PS{PID: pid, Name: "fuzz", Exe: "/bin/fuzz"}, + Params: event.Params{}, + } + switch typ { + case event.Openat, event.Unlink, event.Rename: + evt.Params[params.FilePath] = &event.Param{Name: params.FilePath, Type: params.Path, Value: path} + case event.Connect: + evt.Params[params.NetDport] = &event.Param{Name: params.NetDport, Type: params.Port, Value: port} + case event.Accept: + evt.Params[params.NetSport] = &event.Param{Name: params.NetSport, Type: params.Port, Value: port} + } + return evt +} + +// FuzzApproverNoFalseNegatives is the core soundness property: whatever the +// userspace filter matches, the in-kernel prefilter must also keep. +func FuzzApproverNoFalseNegatives(f *testing.F) { + f.Add(0, 0, uint64(42), "/tmp/payload", uint16(443)) + f.Add(2, 1, uint64(1), "/var/tmp/x", uint16(80)) + f.Add(5, 3, uint64(0), "/etc/passwd", uint16(22)) + f.Add(8, 2, uint64(4242), "", uint16(0)) + + compiled := make([]Filter, len(fuzzExprs)) + plans := make([]*ApproverPlan, len(fuzzExprs)) + for i, expr := range fuzzExprs { + compiled[i] = mustCompileApprover(f, expr) + plans[i] = PlanFromFilter(compiled[i]) + } + + f.Fuzz(func(t *testing.T, exprIdx, typeIdx int, pid uint64, path string, port uint16) { + i := abs(exprIdx) % len(compiled) + typ := fuzzTypes[abs(typeIdx)%len(fuzzTypes)] + + evt := fuzzEvent(typ, pid, path, port) + if !compiled[i].Eval(evt) { + return + } + sample := Sample{Type: typ, PID: pid, Port: port} + if typ == event.Openat || typ == event.Unlink || typ == event.Rename { + sample.Filename = path + } + require.True(t, plans[i].Allows(sample), + "prefilter dropped a userspace match: expr=%q type=%s pid=%d path=%q port=%d", + fuzzExprs[i], typ, pid, path, port) + }) +} + +func abs(n int) int { + if n < 0 { + return -n - 1 + } + return n +} diff --git a/pkg/filter/approver_linux.go b/pkg/filter/approver_linux.go new file mode 100644 index 000000000..fb6af4d1d --- /dev/null +++ b/pkg/filter/approver_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 filter + +import "github.com/rabbitstack/fibratus/pkg/event" + +// AlwaysAllowed reports event types the process snapshotter consumes. Dropping +// one in the kernel would desynchronize process identity from live tasks, so no +// prefilter is ever installed for them regardless of what the rules ask for. +// Mirrored by the leading check in event_approved in c/common/approvers.h. +func AlwaysAllowed(t event.Type) bool { + switch t { + case event.Execve, event.Exit, event.Clone, event.Unknown: + return true + default: + return false + } +} diff --git a/pkg/filter/approver_linux_test.go b/pkg/filter/approver_linux_test.go new file mode 100644 index 000000000..e970c24cf --- /dev/null +++ b/pkg/filter/approver_linux_test.go @@ -0,0 +1,206 @@ +/* + * 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 + +import ( + "testing" + + "github.com/rabbitstack/fibratus/pkg/config" + "github.com/rabbitstack/fibratus/pkg/event" + "github.com/rabbitstack/fibratus/pkg/util/wildcard" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func compileApprover(t *testing.T, expr string) Filter { + t.Helper() + return mustCompileApprover(t, expr) +} + +func mustCompileApprover(tb testing.TB, expr string) Filter { + tb.Helper() + f := New(expr, &config.Config{ + EventSource: config.EventSourceConfig{ + EnableFileIOEvents: true, + EnableNetEvents: true, + EnableMemEvents: true, + }, + Filters: &config.Filters{}, + }) + require.NoError(tb, f.Compile(), expr) + return f +} + +func TestExtractEqualityListPrefix(t *testing.T) { + f := compileApprover(t, "evt.name = 'openat' and file.path startswith '/tmp' and ps.pid in (1, 42)") + ex := f.(ApproverProvider).ApproverExtraction() + require.False(t, ex.Unsupported) + assert.Equal(t, []event.Type{event.Openat}, ex.Types) + assert.ElementsMatch(t, []uint64{1, 42}, ex.PIDs) + assert.Equal(t, []string{"/tmp"}, ex.FilePrefix) +} + +func TestExtractPortList(t *testing.T) { + f := compileApprover(t, "evt.name = 'connect' and net.dport in (80, 443)") + ex := f.(ApproverProvider).ApproverExtraction() + require.False(t, ex.Unsupported) + assert.Equal(t, []uint16{80, 443}, ex.Ports) +} + +func TestExtractUnsupportedShapesDefaultAllow(t *testing.T) { + for _, expr := range []string{ + "evt.name = 'openat' and file.path != '/etc/passwd'", + "evt.name = 'openat' and not (file.path = '/etc/passwd')", + "evt.name = 'openat' and (ps.pid = 1 or file.path = '/tmp/x')", + "evt.name = 'openat' and ps.pid > 1", + "evt.name = 'openat' and lower(file.path) = '/tmp/x'", + } { + plan := PlanFromFilter(compileApprover(t, expr)) + assert.True(t, plan.Policy(event.Openat).DefaultAllow, expr) + } + + seqPlan := PlanFromFilter(compileApprover(t, `sequence +|evt.name = 'execve'| +|evt.name = 'connect'|`)) + assert.True(t, seqPlan.Policy(event.Execve).DefaultAllow) + assert.True(t, seqPlan.Policy(event.Connect).DefaultAllow) +} + +// A list of literal paths needs no wildcard machinery: every element is an +// exact key, so the whole condition resolves in the kernel's hash lookup. +func TestExtractFilePathList(t *testing.T) { + f := compileApprover(t, "evt.name = 'openat' and file.path in ('/etc/passwd', '/etc/shadow')") + ex := f.(ApproverProvider).ApproverExtraction() + require.False(t, ex.Unsupported) + assert.Equal(t, []string{"/etc/passwd", "/etc/shadow"}, ex.FileExact) + assert.Empty(t, ex.FilePrefix) + + plan := PlanFromFilter(f) + pol := plan.Policy(event.Openat) + require.False(t, pol.DefaultAllow) + assert.True(t, pol.RequireFilename) + assert.True(t, plan.Allows(Sample{Type: event.Openat, Filename: "/etc/passwd"})) + assert.True(t, plan.Allows(Sample{Type: event.Openat, Filename: "/etc/shadow"})) + assert.False(t, plan.Allows(Sample{Type: event.Openat, Filename: "/etc/hosts"})) +} + +// ps.name is snapshot state while the kernel can only read the live task comm, +// so a process name predicate must never narrow the in-kernel prefilter. +func TestProcessNameIsNotExtractable(t *testing.T) { + plan := PlanFromFilter(compileApprover(t, "evt.name = 'openat' and ps.name = 'bash'")) + assert.True(t, plan.Policy(event.Openat).DefaultAllow) + + mixed := PlanFromFilter(compileApprover(t, "evt.name = 'openat' and ps.name = 'bash' and file.path startswith '/tmp'")) + assert.True(t, mixed.Policy(event.Openat).DefaultAllow) +} + +func TestExtractMatchesTrailingStar(t *testing.T) { + f := compileApprover(t, "evt.name = 'openat' and file.path matches ('/tmp/*', '/var/tmp/*')") + ex := f.(ApproverProvider).ApproverExtraction() + require.False(t, ex.Unsupported) + assert.Equal(t, []string{"/tmp/", "/var/tmp/"}, ex.FilePrefix) + + plan := PlanFromFilter(f) + assert.True(t, plan.Allows(Sample{Type: event.Openat, Filename: "/tmp/dropper"})) + assert.True(t, plan.Allows(Sample{Type: event.Openat, Filename: "/tmp/a/b/c"})) + assert.True(t, plan.Allows(Sample{Type: event.Openat, Filename: "/var/tmp/x"})) + assert.False(t, plan.Allows(Sample{Type: event.Openat, Filename: "/etc/passwd"})) +} + +// A trailing '*' spans every remaining byte, separators included, so rewriting +// it to a prefix is exact rather than merely conservative. +func TestTrailingStarRewriteMatchesOperator(t *testing.T) { + paths := []string{"/tmp/x", "/tmp/a/b/c", "/tmp/", "/tmpfoo", "/etc/passwd", ""} + for _, pattern := range []string{"/tmp/*", "/tmp/**", "/etc/passwd", "*"} { + literal, prefix, ok := globAsPrefix(pattern) + require.True(t, ok, pattern) + pol := TypePolicy{RequireFilename: true} + switch { + case literal != "": + pol.FileExact = []string{literal} + case prefix != "": + pol.FilePrefix = []string{prefix} + default: + continue // '*' constrains nothing + } + for _, path := range paths { + assert.Equal(t, wildcard.Match(pattern, path, true), matchFilename(pol, path), + "pattern=%q path=%q", pattern, path) + } + } +} + +// Patterns that are not reducible to a prefix have no kernel equivalent, so +// they must widen to default-allow rather than be approximated. +func TestNonPrefixGlobsAreDefaultAllow(t *testing.T) { + for _, expr := range []string{ + "evt.name = 'openat' and file.path matches '/tmp/*/evil'", + "evt.name = 'openat' and file.path matches '*.so'", + "evt.name = 'openat' and file.path matches '/tmp/?vil'", + "evt.name = 'openat' and file.path matches ('/tmp/*', '*.so')", + "evt.name = 'openat' and file.path imatches '/TMP/*'", + } { + plan := PlanFromFilter(compileApprover(t, expr)) + assert.True(t, plan.Policy(event.Openat).DefaultAllow, expr) + } +} + +func TestVacuousStarDoesNotConstrain(t *testing.T) { + plan := PlanFromFilter(compileApprover(t, "evt.name = 'openat' and file.path matches '*'")) + assert.True(t, plan.Policy(event.Openat).DefaultAllow) +} + +func TestBuildPlanIntersectsRequiredFields(t *testing.T) { + pid := compileApprover(t, "evt.name = 'openat' and ps.pid = 7") + path := compileApprover(t, "evt.name = 'openat' and file.path startswith '/tmp'") + mixed := BuildApproverPlan([]Filter{pid, path}) + assert.True(t, mixed.Policy(event.Openat).DefaultAllow, "different required fields cannot be ANDed across rules") + + a := compileApprover(t, "evt.name = 'openat' and file.path startswith '/tmp'") + b := compileApprover(t, "evt.name = 'openat' and file.path startswith '/var'") + union := BuildApproverPlan([]Filter{a, b}) + pol := union.Policy(event.Openat) + require.False(t, pol.DefaultAllow) + assert.True(t, pol.RequireFilename) + assert.ElementsMatch(t, []string{"/tmp", "/var"}, pol.FilePrefix) +} + +func TestAllowsNeverFalseNegative(t *testing.T) { + f := compileApprover(t, "evt.name = 'openat' and file.path startswith '/tmp' and ps.pid = 42") + plan := PlanFromFilter(f) + + keep := Sample{Type: event.Openat, PID: 42, Filename: "/tmp/payload"} + drop := Sample{Type: event.Openat, PID: 7, Filename: "/etc/passwd"} + assert.True(t, plan.Allows(keep)) + assert.False(t, plan.Allows(drop)) + assert.True(t, plan.Allows(Sample{Type: event.Openat, PID: 42, Filename: "/tmp", Truncated: true})) +} + +func TestUnionCLIAndRules(t *testing.T) { + rules := PlanFromFilter(compileApprover(t, "evt.name = 'connect' and net.dport in (80, 443)")) + cli := PlanFromFilter(compileApprover(t, "evt.name = 'connect' and net.dport = 443")) + combined := Union(rules, cli) + pol := combined.Policy(event.Connect) + require.False(t, pol.DefaultAllow) + assert.True(t, pol.RequirePort) + assert.ElementsMatch(t, []uint16{80, 443}, pol.Ports) + assert.True(t, combined.Allows(Sample{Type: event.Connect, Port: 80})) + assert.True(t, combined.Allows(Sample{Type: event.Connect, Port: 443})) + assert.False(t, combined.Allows(Sample{Type: event.Connect, Port: 22})) +} diff --git a/pkg/filter/approver_windows.go b/pkg/filter/approver_windows.go new file mode 100644 index 000000000..36f674911 --- /dev/null +++ b/pkg/filter/approver_windows.go @@ -0,0 +1,27 @@ +//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 filter + +import "github.com/rabbitstack/fibratus/pkg/event" + +// AlwaysAllowed has no Windows counterpart because the ETW source does its own +// approver work in internal/etw/approvers. +func AlwaysAllowed(event.Type) bool { return false } diff --git a/pkg/filter/fields/defs.go b/pkg/filter/fields/defs.go new file mode 100644 index 000000000..4fb2d1d99 --- /dev/null +++ b/pkg/filter/fields/defs.go @@ -0,0 +1,971 @@ +/* + * 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" + // PsUID represents the real user identifier of the process + PsUID Field = "ps.uid" + // PsGID represents the real group identifier of the process + PsGID Field = "ps.gid" + // PsSignal represents the POSIX signal number + PsSignal Field = "ps.signal" + // PsTargetPID represents the target process identifier of kill, ptrace, or process_vm operations + PsTargetPID Field = "ps.target.pid" + // PsPtraceRequest represents the ptrace request code + PsPtraceRequest Field = "ps.ptrace.request" + // PsPrctlOption represents the prctl option code + PsPrctlOption Field = "ps.prctl.option" + // PsCloneFlags represents the clone flags bitmask + PsCloneFlags Field = "ps.clone_flags" + // 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" + // ThreadTID is the thread identifier + ThreadTID Field = "thread.tid" + // 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" + // EvtRetval represents the syscall return value + EvtRetval Field = "evt.retval" + // EvtSyscallID represents the raw architecture-specific syscall number + EvtSyscallID Field = "evt.syscall_id" + // 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" + + // 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" + // NetFamily represents the socket address family + NetFamily Field = "net.family" + // NetUnixPath represents the filesystem path of an AF_UNIX socket + NetUnixPath Field = "net.unix_path" + // NetFD represents the socket file descriptor + NetFD Field = "net.fd" + + // 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" + // FilePathTarget represents the destination path of a rename or similar source/target file operation + FilePathTarget Field = "file.path.target" + // FileDirFD represents a directory file descriptor, including AT_FDCWD + FileDirFD Field = "file.dirfd" + // FileFD represents a file descriptor + FileFD Field = "file.fd" + // FileFlags represents the raw openat, unlinkat, or renameat flags bitmask + FileFlags Field = "file.flags" + // FileMode represents the file creation mode supplied to openat + FileMode Field = "file.mode" + // 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" + // MemMmapFlags represents the mmap flags bitmask + MemMmapFlags Field = "mem.mmap.flags" + // MemMmapFD represents the file descriptor backing a mapping + MemMmapFD Field = "mem.mmap.fd" + // MemMmapOffset represents the file offset of a memory mapping + MemMmapOffset Field = "mem.mmap.offset" + // MemTargetPID represents the target process identifier of a process_vm operation + MemTargetPID Field = "mem.target.pid" + + // 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" +) + +// 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) 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) 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{ + 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}, + EvtSeq: {EvtSeq, "event sequence number", params.Uint64, []string{"evt.seq > 666"}, 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.String, []string{"evt.name = 'CreateThread'"}, nil, nil}, + EvtCategory: {EvtCategory, "event category", params.String, []string{"evt.category = 'registry'"}, nil, nil}, + EvtDesc: {EvtDesc, "event description", params.String, []string{"evt.desc contains 'Creates a new process'"}, nil, nil}, + EvtHost: {EvtHost, "host name on which the event was produced", params.String, []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.String, []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.String, []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 + }}}, + PsName: {PsName, "process image name including the file extension", params.String, []string{"ps.name contains 'firefox'"}, nil, nil}, + PsCmdline: {PsCmdline, "process command line", params.String, []string{"ps.cmdline contains 'java'"}, nil, nil}, + PsExe: {PsExe, "full name of the process' executable", params.String, []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.String, []string{"ps.cwd = 'C:\\Users\\Default'"}, nil, nil}, + PsUsername: {PsUsername, "process username", params.String, []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", params.String, []string{"ps.parent.name contains 'cmd.exe'"}, nil, nil}, + PsParentCmdline: {PsParentCmdline, "parent process command line", params.String, []string{"ps.parent.cmdline contains 'java'"}, nil, nil}, + PsParentExe: {PsParentExe, "full name of the parent process' executable", params.String, []string{"ps.parent.exe = 'C:\\Windows\\system32\\explorer.exe'"}, 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/fields/defs_linux.go b/pkg/filter/fields/defs_linux.go new file mode 100644 index 000000000..8e9805702 --- /dev/null +++ b/pkg/filter/fields/defs_linux.go @@ -0,0 +1,70 @@ +//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 init() { + fields[EvtRetval] = FieldInfo{EvtRetval, "syscall return value", params.Int64, []string{"evt.retval < 0"}, nil, nil} + fields[EvtSyscallID] = FieldInfo{EvtSyscallID, "raw architecture-specific syscall number", params.Uint32, []string{"evt.syscall_id = 59"}, nil, nil} + fields[PsPid] = FieldInfo{PsPid, "process identifier", params.Uint64, []string{"ps.pid = 1024"}, nil, nil} + fields[PsPpid] = FieldInfo{PsPpid, "parent process identifier", params.Uint64, []string{"ps.ppid = 45"}, nil, nil} + fields[PsParentPid] = FieldInfo{PsParentPid, "parent process id", params.Uint64, []string{"ps.parent.pid = 4"}, nil, nil} + fields[PsUUID] = FieldInfo{PsUUID, "unique process identifier", params.Uint64, []string{"ps.uuid > 6000054355"}, nil, nil} + fields[PsParentUUID] = FieldInfo{PsParentUUID, "unique parent process identifier", params.Uint64, []string{"ps.parent.uuid > 6000054355"}, nil, nil} + fields[PsUID] = FieldInfo{PsUID, "real user identifier of the process", params.Uint32, []string{"ps.uid = 0"}, nil, nil} + fields[PsGID] = FieldInfo{PsGID, "real group identifier of the process", params.Uint32, []string{"ps.gid = 0"}, nil, nil} + fields[PsParentArgs] = FieldInfo{PsParentArgs, "parent process command line arguments", params.Slice, []string{"ps.parent.args in ('-c', 'bash')"}, nil, nil} + fields[PsParentCwd] = FieldInfo{PsParentCwd, "parent process current working directory", params.String, []string{"ps.parent.cwd = '/home/user'"}, nil, nil} + fields[PsParentUsername] = FieldInfo{PsParentUsername, "parent process username", params.String, []string{"ps.parent.username = 'root'"}, nil, nil} + fields[PsParentEnvs] = FieldInfo{PsParentEnvs, "parent process environment variables", params.Slice, []string{"ps.parent.envs in ('PATH:/usr/bin')"}, nil, nil} + fields[PsSignal] = FieldInfo{PsSignal, "POSIX signal number", params.Int64, []string{"ps.signal = 9"}, nil, nil} + fields[PsTargetPID] = FieldInfo{PsTargetPID, "target process identifier of kill, ptrace, or process_vm operations. Signal targets keep the pid_t sign, where zero is the caller process group, -1 is every permitted process, and any other negative value is the process group of its absolute value", params.Int64, []string{"ps.target.pid = 4242", "ps.target.pid < 0"}, nil, nil} + fields[PsPtraceRequest] = FieldInfo{PsPtraceRequest, "ptrace request code", params.Int64, []string{"ps.ptrace.request = 16"}, nil, nil} + fields[PsPrctlOption] = FieldInfo{PsPrctlOption, "prctl option code", params.Int64, []string{"ps.prctl.option = 15"}, nil, nil} + fields[PsCloneFlags] = FieldInfo{PsCloneFlags, "clone flags bitmask", params.Uint64, []string{"ps.clone_flags = 0"}, nil, nil} + fields[FilePath] = FieldInfo{FilePath, "full file path", params.String, []string{"file.path = '/etc/passwd'"}, nil, nil} + fields[FilePathStem] = FieldInfo{FilePathStem, "full file path without extension", params.String, []string{"file.path.stem = '/tmp/secret'"}, nil, nil} + fields[FileName] = FieldInfo{FileName, "file base name", params.String, []string{"file.name = 'passwd'"}, nil, nil} + fields[FileExtension] = FieldInfo{FileExtension, "file extension", params.String, []string{"file.extension = '.so'"}, nil, nil} + fields[FilePathTarget] = FieldInfo{FilePathTarget, "destination path of a rename or similar source/target file operation", params.String, []string{"file.path.target = '/tmp/renamed'"}, nil, nil} + fields[FileDirFD] = FieldInfo{FileDirFD, "directory file descriptor, including AT_FDCWD", params.Int64, []string{"file.dirfd < 0"}, nil, nil} + fields[FileFD] = FieldInfo{FileFD, "file descriptor returned by openat", params.Int64, []string{"file.fd = 3"}, nil, nil} + fields[FileFlags] = FieldInfo{FileFlags, "raw openat, unlinkat, or renameat flags bitmask", params.Uint64, []string{"file.flags = 0"}, nil, nil} + fields[FileMode] = FieldInfo{FileMode, "file creation mode supplied to openat", params.Uint64, []string{"file.mode = 420"}, nil, nil} + fields[NetDIP] = FieldInfo{NetDIP, "destination IP address", params.IP, []string{"net.dip = 172.17.0.3"}, nil, nil} + fields[NetSIP] = FieldInfo{NetSIP, "source IP address", params.IP, []string{"net.sip = 127.0.0.1"}, nil, nil} + fields[NetDport] = FieldInfo{NetDport, "destination port", params.Uint16, []string{"net.dport in (80, 443, 8080)"}, nil, nil} + fields[NetSport] = FieldInfo{NetSport, "source port", params.Uint16, []string{"net.sport != 3306"}, nil, nil} + fields[NetFamily] = FieldInfo{NetFamily, "socket address family", params.Uint16, []string{"net.family = 2"}, nil, nil} + fields[NetUnixPath] = FieldInfo{NetUnixPath, "filesystem path of an AF_UNIX socket", params.String, []string{"net.unix_path = '/tmp/app.sock'"}, nil, nil} + fields[NetFD] = FieldInfo{NetFD, "socket file descriptor", params.Int64, []string{"net.fd = 5"}, nil, nil} + fields[MemBaseAddress] = FieldInfo{MemBaseAddress, "region base address", params.Uint64, []string{"mem.address = 8192"}, nil, nil} + fields[MemRegionSize] = FieldInfo{MemRegionSize, "region size", params.Uint64, []string{"mem.size > 4096"}, nil, nil} + fields[MemProtection] = FieldInfo{MemProtection, "mapping protection bitmask", params.Uint32, []string{"mem.protection = 3"}, nil, nil} + fields[MemMmapFlags] = FieldInfo{MemMmapFlags, "mmap flags bitmask", params.Uint64, []string{"mem.mmap.flags = 1"}, nil, nil} + fields[MemMmapFD] = FieldInfo{MemMmapFD, "file descriptor backing a mapping", params.Int64, []string{"mem.mmap.fd = 3"}, nil, nil} + fields[MemMmapOffset] = FieldInfo{MemMmapOffset, "file offset of a memory mapping", params.Uint64, []string{"mem.mmap.offset = 0"}, nil, nil} + fields[MemTargetPID] = FieldInfo{MemTargetPID, "target process identifier of a process_vm operation", params.Int64, []string{"mem.target.pid = 4242"}, nil, nil} + fields[ThreadTID] = FieldInfo{ThreadTID, "thread identifier", params.Uint64, []string{"thread.tid = 1024"}, nil, nil} + fields[ThreadPID] = FieldInfo{ThreadPID, "thread group identifier of the thread", params.Uint64, []string{"thread.pid = 1024"}, 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..6a1242c8a --- /dev/null +++ b/pkg/filter/fields/defs_linux_test.go @@ -0,0 +1,76 @@ +//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 TestFields(t *testing.T) { + require.True(t, IsField(string(EvtName))) + require.True(t, IsField(string(PsName))) + require.True(t, IsField(string(PsParentExe))) + require.True(t, IsField(string(PsUUID))) + require.True(t, IsField(string(PsUID))) + require.True(t, IsField(string(FilePath))) + require.True(t, IsField(string(FilePathTarget))) + require.True(t, IsField(string(NetDIP))) + require.True(t, IsField(string(NetFamily))) + require.True(t, IsField(string(MemBaseAddress))) + require.True(t, IsField(string(MemMmapFlags))) + require.True(t, IsField(string(ThreadTID))) + require.True(t, IsField(string(EvtRetval))) + require.True(t, IsField(string(EvtSyscallID))) + require.False(t, IsField("evt.truncated")) + require.False(t, IsField("file.truncated")) + 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.Equal(t, params.Int64, EvtRetval.Type()) + require.Equal(t, params.IP, NetDIP.Type()) + require.Equal(t, params.Uint32, MemProtection.Type()) +} + +func TestExcludesWindowsOnlyFields(t *testing.T) { + unavailable := []Field{ + KevtPID, KevtTID, KevtSeq, KevtName, KevtArg, KevtCPU, KevtHost, + PsComm, PsSID, PsDomain, PsIsWOW64Field, PsPeNumSections, + RegistryPath, PeEntrypoint, ImagePath, ModulePath, DllPath, + DNSName, FileObject, FileOperation, FileIsDLL, + MemPageType, MemAllocType, MemProtectionMask, ThreadTEB, + EvtIsDirectSyscall, EvtIsIndirectSyscall, + } + for _, field := range unavailable { + require.False(t, IsField(string(field)), "%s should be unavailable on Linux", field) + } +} + +func TestKevtDeprecationAbsentOnLinux(t *testing.T) { + deprecated, d := IsDeprecated(KevtArg) + require.False(t, deprecated) + require.Nil(t, d) +} diff --git a/pkg/filter/fields/defs_windows.go b/pkg/filter/fields/defs_windows.go new file mode 100644 index 000000000..fbc76a21a --- /dev/null +++ b/pkg/filter/fields/defs_windows.go @@ -0,0 +1,339 @@ +//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" +) + +// isNumber is the field argument validation function that +// returns true if all characters are digits. +var isNumber = func(s string) bool { + for _, c := range s { + if !unicode.IsNumber(c) { + return false + } + } + return true +} + +func init() { + fields[KevtPID] = FieldInfo{KevtPID, "process identifier generating the event", params.Uint32, []string{"kevt.pid = 6"}, &Deprecation{Since: "3.0.0", Fields: []Field{EvtPID}}, nil} + fields[KevtTID] = FieldInfo{KevtTID, "thread identifier generating the event", params.Uint32, []string{"kevt.tid = 1024"}, &Deprecation{Since: "3.0.0", Fields: []Field{EvtTID}}, nil} + fields[KevtSeq] = FieldInfo{KevtSeq, "event sequence number", params.Uint64, []string{"kevt.seq > 666"}, &Deprecation{Since: "3.0.0", Fields: []Field{EvtSeq}}, nil} + fields[KevtCPU] = FieldInfo{KevtCPU, "logical processor core where the event was generated", params.Uint8, []string{"kevt.cpu = 2"}, &Deprecation{Since: "3.0.0", Fields: []Field{EvtCPU}}, nil} + fields[KevtName] = FieldInfo{KevtName, "symbolical event name", params.AnsiString, []string{"kevt.name = 'CreateThread'"}, &Deprecation{Since: "3.0.0", Fields: []Field{EvtName}}, nil} + fields[KevtCategory] = FieldInfo{KevtCategory, "event category", params.AnsiString, []string{"kevt.category = 'registry'"}, &Deprecation{Since: "3.0.0", Fields: []Field{EvtCategory}}, nil} + fields[KevtDesc] = FieldInfo{KevtDesc, "event description", params.AnsiString, []string{"kevt.desc contains 'Creates a new process'"}, &Deprecation{Since: "3.0.0", Fields: []Field{EvtDesc}}, nil} + fields[KevtHost] = FieldInfo{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} + fields[KevtTime] = FieldInfo{KevtTime, "event timestamp as a time string", params.Time, []string{"kevt.time = '17:05:32'"}, &Deprecation{Since: "3.0.0", Fields: []Field{EvtTime}}, nil} + fields[KevtTimeHour] = FieldInfo{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} + fields[KevtTimeMin] = FieldInfo{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} + fields[KevtTimeSec] = FieldInfo{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} + fields[KevtTimeNs] = FieldInfo{KevtTimeNs, "nanoseconds specified by event timestamp", params.Int64, []string{"kevt.time.ns > 1591191629102337000"}, &Deprecation{Since: "3.0.0", Fields: []Field{EvtTimeNs}}, nil} + fields[KevtDate] = FieldInfo{KevtDate, "event timestamp as a date string", params.Time, []string{"kevt.date = '2018-03-03'"}, &Deprecation{Since: "3.0.0", Fields: []Field{EvtDate}}, nil} + fields[KevtDateDay] = FieldInfo{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} + fields[KevtDateMonth] = FieldInfo{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} + fields[KevtDateYear] = FieldInfo{KevtDateYear, "year on which the event occurred", params.Uint32, []string{"kevt.date.y = 2020"}, &Deprecation{Since: "3.0.0", Fields: []Field{EvtDateYear}}, nil} + fields[KevtDateTz] = FieldInfo{KevtDateTz, "time zone associated with the event timestamp", params.AnsiString, []string{"kevt.date.tz = 'UTC'"}, &Deprecation{Since: "3.0.0", Fields: []Field{EvtDateTz}}, nil} + fields[KevtDateWeek] = FieldInfo{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} + fields[KevtDateWeekday] = FieldInfo{KevtDateWeekday, "week day on which the event occurred", params.AnsiString, []string{"kevt.date.weekday = 'Monday'"}, &Deprecation{Since: "3.0.0", Fields: []Field{EvtDateWeekday}}, nil} + fields[KevtNparams] = FieldInfo{KevtNparams, "number of parameters", params.Int8, []string{"kevt.nparams > 2"}, &Deprecation{Since: "3.0.0", Fields: []Field{EvtNparams}}, nil} + fields[KevtArg] = FieldInfo{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 + }}} + fields[PsPid] = FieldInfo{PsPid, "process identifier", params.PID, []string{"ps.pid = 1024"}, nil, nil} + fields[PsPpid] = FieldInfo{PsPpid, "parent process identifier", params.PID, []string{"ps.ppid = 45"}, nil, nil} + fields[PsParentPid] = FieldInfo{PsParentPid, "parent process id", params.Uint32, []string{"ps.parent.pid = 4"}, nil, nil} + fields[EvtIsDirectSyscall] = FieldInfo{EvtIsDirectSyscall, "indicates if the event is performing a direct syscall", params.Bool, []string{"evt.is_direct_syscall = true"}, nil, nil} + fields[EvtIsIndirectSyscall] = FieldInfo{EvtIsIndirectSyscall, "indicates if the event is performing an indirect syscall", params.Bool, []string{"evt.is_indirect_syscall = true"}, nil, nil} + fields[PsComm] = FieldInfo{PsComm, "process command line", params.UnicodeString, []string{"ps.comm contains 'java'"}, &Deprecation{Since: "1.10.0", Fields: []Field{PsCmdline}}, nil} + fields[PsSID] = FieldInfo{PsSID, "security identifier under which this process is run", params.UnicodeString, []string{"ps.sid contains 'SYSTEM'"}, nil, nil} + fields[PsSessionID] = FieldInfo{PsSessionID, "unique identifier for the current session", params.Int16, []string{"ps.sessionid = 1"}, nil, nil} + fields[PsDomain] = FieldInfo{PsDomain, "process domain", params.UnicodeString, []string{"ps.domain contains 'SERVICE'"}, nil, nil} + fields[PsHandleNames] = FieldInfo{PsHandleNames, "allocated process handle names", params.Slice, []string{"ps.handles in ('\\BaseNamedObjects\\__ComCatalogCache__')"}, nil, nil} + fields[PsHandleTypes] = FieldInfo{PsHandleTypes, "allocated process handle types", params.Slice, []string{"ps.handle.types in ('Key', 'Mutant', 'Section')"}, nil, nil} + fields[PsDTB] = FieldInfo{PsDTB, "process directory table base address", params.Address, []string{"ps.dtb = '7ffe0000'"}, nil, nil} + fields[PsModuleNames] = FieldInfo{PsModuleNames, "modules loaded by the process", params.Slice, []string{"ps.modules in ('crypt32.dll', 'xul.dll')"}, nil, nil} + fields[PsParentComm] = FieldInfo{PsParentComm, "parent process command line", params.UnicodeString, []string{"ps.parent.comm contains 'java'"}, &Deprecation{Since: "1.10.0", Fields: []Field{PsParentCmdline}}, nil} + fields[PsParentArgs] = FieldInfo{PsParentArgs, "parent process command line arguments", params.Slice, []string{"ps.parent.args in ('/cdir', '/-C')"}, nil, nil} + fields[PsParentCwd] = FieldInfo{PsParentCwd, "parent process current working directory", params.UnicodeString, []string{"ps.parent.cwd = 'C:\\Temp'"}, nil, nil} + fields[PsParentSID] = FieldInfo{PsParentSID, "security identifier under which the parent process is run", params.UnicodeString, []string{"ps.parent.sid contains 'SYSTEM'"}, nil, nil} + fields[PsParentDomain] = FieldInfo{PsParentDomain, "parent process domain", params.UnicodeString, []string{"ps.parent.domain contains 'SERVICE'"}, nil, nil} + fields[PsParentUsername] = FieldInfo{PsParentUsername, "parent process username", params.UnicodeString, []string{"ps.parent.username contains 'system'"}, nil, nil} + fields[PsParentSessionID] = FieldInfo{PsParentSessionID, "unique identifier for the current session of parent process", params.Int16, []string{"ps.parent.sessionid = 1"}, nil, nil} + fields[PsParentEnvs] = FieldInfo{PsParentEnvs, "parent process environment variables", params.Slice, []string{"ps.parent.envs in ('MOZ_CRASHREPORTER_DATA_DIRECTORY')"}, nil, nil} + fields[PsParentHandles] = FieldInfo{PsParentHandles, "allocated parent process handle names", params.Slice, []string{"ps.parent.handles in ('\\BaseNamedObjects\\__ComCatalogCache__')"}, nil, nil} + fields[PsParentHandleTypes] = FieldInfo{PsParentHandleTypes, "allocated parent process handle types", params.Slice, []string{"ps.parent.handle.types in ('File', 'SymbolicLink')"}, nil, nil} + fields[PsParentDTB] = FieldInfo{PsParentDTB, "parent process directory table base address", params.Address, []string{"ps.parent.dtb = '7ffe0000'"}, nil, nil} + fields[PsAccessMask] = FieldInfo{PsAccessMask, "process desired access rights", params.AnsiString, []string{"ps.access.mask = '0x1400'"}, nil, nil} + fields[PsAccessMaskNames] = FieldInfo{PsAccessMaskNames, "process desired access rights as a string list", params.Slice, []string{"ps.access.mask.names in ('SUSPEND_RESUME')"}, nil, nil} + fields[PsAccessStatus] = FieldInfo{PsAccessStatus, "process access status", params.UnicodeString, []string{"ps.access.status = 'access is denied.'"}, nil, nil} + fields[PsUUID] = FieldInfo{PsUUID, "unique process identifier", params.Uint64, []string{"ps.uuid > 6000054355"}, nil, nil} + fields[PsParentUUID] = FieldInfo{PsParentUUID, "unique parent process identifier", params.Uint64, []string{"ps.parent.uuid > 6000054355"}, nil, nil} + fields[PsIsWOW64Field] = FieldInfo{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} + fields[PsIsPackagedField] = FieldInfo{PsIsPackagedField, "indicates if the process generating the event is packaged with the MSIX technology", params.Bool, []string{"ps.is_packaged"}, nil, nil} + fields[PsIsProtectedField] = FieldInfo{PsIsProtectedField, "indicates if the process generating the event is a protected process", params.Bool, []string{"ps.is_protected"}, nil, nil} + fields[PsParentIsWOW64Field] = FieldInfo{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} + fields[PsParentIsPackagedField] = FieldInfo{PsParentIsPackagedField, "indicates if the parent process generating the event is packaged with the MSIX technology", params.Bool, []string{"ps.parent.is_packaged"}, nil, nil} + fields[PsParentIsProtectedField] = FieldInfo{PsParentIsProtectedField, "indicates if the the parent process generating the event is a protected process", params.Bool, []string{"ps.parent.is_protected"}, nil, nil} + fields[PsAncestor] = FieldInfo{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}} + fields[PsTokenIntegrityLevel] = FieldInfo{PsTokenIntegrityLevel, "process token integrity level", params.UnicodeString, []string{"ps.token.integrity_level = 'SYSTEM'"}, nil, nil} + fields[PsTokenIsElevated] = FieldInfo{PsTokenIsElevated, "indicates if the process token is elevated", params.Bool, []string{"ps.token.is_elevated = true"}, nil, nil} + fields[PsTokenElevationType] = FieldInfo{PsTokenElevationType, "process token elevation type", params.AnsiString, []string{"ps.token.elevation_type = 'LIMITED'"}, nil, nil} + fields[PsParentTokenIntegrityLevel] = FieldInfo{PsParentTokenIntegrityLevel, "parent process token integrity level", params.UnicodeString, []string{"ps.parent.token.integrity_level = 'HIGH'"}, nil, nil} + fields[PsParentTokenIsElevated] = FieldInfo{PsParentTokenIsElevated, "indicates if the parent process token is elevated", params.Bool, []string{"ps.parent.token.is_elevated = true"}, nil, nil} + fields[PsParentTokenElevationType] = FieldInfo{PsParentTokenElevationType, "parent process token elevation type", params.AnsiString, []string{"ps.parent.token.elevation_type = 'LIMITED'"}, nil, nil} + fields[PsSignatureExists] = FieldInfo{PsSignatureExists, "indicates if the process executable has a valid signature", params.Bool, []string{"ps.signature.exists"}, nil, nil} + fields[PsSignatureTrusted] = FieldInfo{PsSignatureTrusted, "indicates if the process executable signature certificate chain is trusted", params.Bool, []string{"ps.signature.trusted"}, nil, nil} + fields[PsSignatureSerial] = FieldInfo{PsSignatureSerial, "represents signature serial number", params.UnicodeString, []string{"ps.signature.serial = '330000023241fb59996dcc4dff000000000232'"}, nil, nil} + fields[PsSignatureSubject] = FieldInfo{PsSignatureSubject, "represents signature subject", params.UnicodeString, []string{"ps.signature.subject contains 'Washington, Redmond, Microsoft Corporation'"}, nil, nil} + fields[PsSignatureIssuer] = FieldInfo{PsSignatureIssuer, "represents signature CA", params.UnicodeString, []string{"ps.signature.issuer contains 'Washington, Redmond, Microsoft Corporation'"}, nil, nil} + fields[PsSignatureAfter] = FieldInfo{PsSignatureAfter, "represents certificate expiration date", params.Time, []string{"ps.signature.after contains '2024-02-01 00:05:42 +0000 UTC'"}, nil, nil} + fields[PsSignatureBefore] = FieldInfo{PsSignatureBefore, "represents certificate enrollment date", params.Time, []string{"ps.signature.before contains '2024-02-01 00:05:42 +0000 UTC'"}, nil, nil} + fields[PsPeNumSections] = FieldInfo{PsPeNumSections, "number of PE sections", params.Uint16, []string{"ps.pe.nsections < 5"}, nil, nil} + fields[PsPeNumSymbols] = FieldInfo{PsPeNumSymbols, "number of entries in the symbol table", params.Uint32, []string{"ps.pe.nsymbols > 230"}, nil, nil} + fields[PsPeBaseAddress] = FieldInfo{PsPeBaseAddress, "executable base address", params.Address, []string{"ps.pe.address.base = '140000000'"}, nil, nil} + fields[PsPeEntrypoint] = FieldInfo{PsPeEntrypoint, "address of the entrypoint function", params.Address, []string{"ps.pe.address.entrypoint = '20110'"}, nil, nil} + fields[PsPeSymbols] = FieldInfo{PsPeSymbols, "imported symbols", params.Slice, []string{"ps.pe.symbols in ('GetTextFaceW', 'GetProcessHeap')"}, nil, nil} + fields[PsPeImports] = FieldInfo{PsPeImports, "imported dynamic linked libraries", params.Slice, []string{"ps.pe.imports in ('msvcrt.dll', 'GDI32.dll'"}, nil, nil} + fields[PsPeResources] = FieldInfo{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 + }}} + fields[PsPeCompany] = FieldInfo{PsPeCompany, "internal company name of the file provided at compile-time", params.UnicodeString, []string{"ps.pe.company = 'Microsoft Corporation'"}, nil, nil} + fields[PsPeCopyright] = FieldInfo{PsPeCopyright, "copyright notice for the file emitted at compile-time", params.UnicodeString, []string{"ps.pe.copyright = '© Microsoft Corporation'"}, nil, nil} + fields[PsPeDescription] = FieldInfo{PsPeDescription, "internal description of the file provided at compile-time", params.UnicodeString, []string{"ps.pe.description = 'Notepad'"}, nil, nil} + fields[PsPeFileName] = FieldInfo{PsPeFileName, "original file name supplied at compile-time", params.UnicodeString, []string{"ps.pe.file.name = 'NOTEPAD.EXE'"}, nil, nil} + fields[PsPeFileVersion] = FieldInfo{PsPeFileVersion, "file version supplied at compile-time", params.UnicodeString, []string{"ps.pe.file.version = '10.0.18362.693 (WinBuild.160101.0800)'"}, nil, nil} + fields[PsPeProduct] = FieldInfo{PsPeProduct, "internal product name of the file provided at compile-time", params.UnicodeString, []string{"ps.pe.product = 'Microsoft® Windows® Operating System'"}, nil, nil} + fields[PsPeProductVersion] = FieldInfo{PsPeProductVersion, "internal product version of the file provided at compile-time", params.UnicodeString, []string{"ps.pe.product.version = '10.0.18362.693'"}, nil, nil} + fields[PsPeImphash] = FieldInfo{PsPeImphash, "import hash", params.AnsiString, []string{"pe.impash = '5d3861c5c547f8a34e471ba273a732b2'"}, nil, nil} + fields[PsPeIsDotnet] = FieldInfo{PsPeIsDotnet, "indicates if PE contains CLR data", params.Bool, []string{"ps.pe.is_dotnet"}, nil, nil} + fields[PsPeAnomalies] = FieldInfo{PsPeAnomalies, "contains PE anomalies detected during parsing", params.Slice, []string{"ps.pe.anomalies in ('number of sections is 0')"}, nil, nil} + fields[PsPeIsModified] = FieldInfo{PsPeIsModified, "indicates if disk and in-memory PE headers differ", params.Bool, []string{"ps.pe.is_modified"}, nil, nil} + fields[ThreadBasePrio] = FieldInfo{ThreadBasePrio, "scheduler priority of the thread", params.Int8, []string{"thread.prio = 5"}, nil, nil} + fields[ThreadIOPrio] = FieldInfo{ThreadIOPrio, "I/O priority hint for scheduling I/O operations", params.Int8, []string{"thread.io.prio = 4"}, nil, nil} + fields[ThreadPagePrio] = FieldInfo{ThreadPagePrio, "memory page priority hint for memory pages accessed by the thread", params.Int8, []string{"thread.page.prio = 12"}, nil, nil} + fields[ThreadKstackBase] = FieldInfo{ThreadKstackBase, "base address of the thread's kernel space stack", params.Address, []string{"thread.kstack.base = 'a65d800000'"}, nil, nil} + fields[ThreadKstackLimit] = FieldInfo{ThreadKstackLimit, "limit of the thread's kernel space stack", params.Address, []string{"thread.kstack.limit = 'a85d800000'"}, nil, nil} + fields[ThreadUstackBase] = FieldInfo{ThreadUstackBase, "base address of the thread's user space stack", params.Address, []string{"thread.ustack.base = '7ffe0000'"}, nil, nil} + fields[ThreadUstackLimit] = FieldInfo{ThreadUstackLimit, "limit of the thread's user space stack", params.Address, []string{"thread.ustack.limit = '8ffe0000'"}, nil, nil} + fields[ThreadEntrypoint] = FieldInfo{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} + fields[ThreadStartAddress] = FieldInfo{ThreadStartAddress, "thread start address", params.Address, []string{"thread.start_address = '7efe0000'"}, nil, nil} + fields[ThreadStartAddressSymbol] = FieldInfo{ThreadStartAddressSymbol, "thread start address symbol", params.UnicodeString, []string{"thread.start_address.symbol = 'LoadModule'"}, nil, nil} + fields[ThreadStartAddressModule] = FieldInfo{ThreadStartAddressModule, "thread start address module", params.UnicodeString, []string{"thread.start_address.module endswith 'kernel32.dll'"}, nil, nil} + fields[ThreadPID] = FieldInfo{ThreadPID, "the process identifier where the thread is created", params.Uint32, []string{"evt.pid != thread.pid"}, nil, nil} + fields[ThreadTEB] = FieldInfo{ThreadTEB, "the base address of the thread environment block", params.Address, []string{"thread.teb_address = '8f30893000'"}, nil, nil} + fields[ThreadAccessMask] = FieldInfo{ThreadAccessMask, "thread desired access rights", params.AnsiString, []string{"thread.access.mask = '0x1fffff'"}, nil, nil} + fields[ThreadAccessMaskNames] = FieldInfo{ThreadAccessMaskNames, "thread desired access rights as a string list", params.Slice, []string{"thread.access.mask.names in ('IMPERSONATE')"}, nil, nil} + fields[ThreadAccessStatus] = FieldInfo{ThreadAccessStatus, "thread access status", params.UnicodeString, []string{"thread.access.status = 'success'"}, nil, nil} + fields[ThreadCallstackSummary] = FieldInfo{ThreadCallstackSummary, "callstack summary", params.UnicodeString, []string{"thread.callstack.summary contains 'ntdll.dll|KERNELBASE.dll'"}, nil, nil} + fields[ThreadCallstackKernelSummary] = FieldInfo{ThreadCallstackKernelSummary, "kernel thread callstack summary", params.UnicodeString, []string{"thread.callstack.kernel_summary contains 'fileinfo.sys|ntoskrnl.exe|FLTMGR.SYS|ntoskrnl.exe'"}, nil, nil} + fields[ThreadCallstackDetail] = FieldInfo{ThreadCallstackDetail, "detailed information of each stack frame", params.UnicodeString, []string{"thread.callstack.detail contains 'KERNELBASE.dll!CreateProcessW'"}, nil, nil} + fields[ThreadCallstackModules] = FieldInfo{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}} + fields[ThreadCallstackSymbols] = FieldInfo{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}} + fields[ThreadCallstackAllocationSizes] = FieldInfo{ThreadCallstackAllocationSizes, "allocation sizes of private pages", params.Slice, []string{"thread.callstack.allocation_sizes > 10000"}, nil, nil} + fields[ThreadCallstackProtections] = FieldInfo{ThreadCallstackProtections, "page protections masks of each frame", params.Slice, []string{"thread.callstack.protections in ('RWX', 'WX')"}, nil, nil} + fields[ThreadCallstackCallsiteLeadingAssembly] = FieldInfo{ThreadCallstackCallsiteLeadingAssembly, "callsite leading assembly instructions", params.Slice, []string{"thread.callstack.callsite_leading_assembly in ('mov r10,rcx', 'syscall')"}, nil, nil} + fields[ThreadCallstackCallsiteTrailingAssembly] = FieldInfo{ThreadCallstackCallsiteTrailingAssembly, "callsite trailing assembly instructions", params.Slice, []string{"thread.callstack.callsite_trailing_assembly in ('add esp, 0xab')"}, nil, nil} + fields[ThreadCallstackIsUnbacked] = FieldInfo{ThreadCallstackIsUnbacked, "indicates if the callstack contains unbacked regions", params.Bool, []string{"thread.callstack.is_unbacked"}, nil, nil} + fields[ThreadCallstackAddresses] = FieldInfo{ThreadCallstackAddresses, "list of all stack return addresses", params.Slice, []string{"thread.callstack.addresses in ('7ffb5c1d0396')"}, nil, nil} + fields[ThreadCallstackFinalUserModuleName] = FieldInfo{ThreadCallstackFinalUserModuleName, "final user space stack frame module name", params.UnicodeString, []string{"thread.callstack.final_user_module.name != 'ntdll.dll'"}, nil, nil} + fields[ThreadCallstackFinalUserModulePath] = FieldInfo{ThreadCallstackFinalUserModulePath, "final user space stack frame module path", params.UnicodeString, []string{"thread.callstack.final_user_module.path imatches '?:\\Windows\\System32\\ntdll.dll'"}, nil, nil} + fields[ThreadCallstackFinalUserSymbolName] = FieldInfo{ThreadCallstackFinalUserSymbolName, "final user space stack symbol name", params.UnicodeString, []string{"thread.callstack.final_user_symbol.name imatches 'CreateProcess*'"}, nil, nil} + fields[ThreadCallstackFinalKernelModuleName] = FieldInfo{ThreadCallstackFinalKernelModuleName, "final kernel space stack frame module name", params.UnicodeString, []string{"thread.callstack.final_kernel_module.name = 'FLTMGR.SYS'"}, nil, nil} + fields[ThreadCallstackFinalKernelModulePath] = FieldInfo{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} + fields[ThreadCallstackFinalKernelSymbolName] = FieldInfo{ThreadCallstackFinalKernelSymbolName, "final kernel space stack symbol name", params.UnicodeString, []string{"thread.callstack.final_kernel_symbol.name = 'FltGetStreamContext'"}, nil, nil} + fields[ThreadCallstackFinalUserModuleSignatureExists] = FieldInfo{ThreadCallstackFinalUserModuleSignatureExists, "signature status of the final user space stack frame module", params.Bool, []string{"thread.callstack.final_user_module.signature.exists = true"}, nil, nil} + fields[ThreadCallstackFinalUserModuleSignatureTrusted] = FieldInfo{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} + fields[ThreadCallstackFinalUserModuleSignatureIssuer] = FieldInfo{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} + fields[ThreadCallstackFinalUserModuleSignatureSubject] = FieldInfo{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} + fields[ImagePath] = FieldInfo{ImagePath, "full image path", params.UnicodeString, []string{"image.path = 'C:\\Windows\\System32\\advapi32.dll'"}, &Deprecation{Since: "3.0.0", Fields: []Field{ModulePath}}, nil} + fields[ImageName] = FieldInfo{ImageName, "image name", params.UnicodeString, []string{"image.name = 'advapi32.dll'"}, &Deprecation{Since: "3.0.0", Fields: []Field{ModuleName}}, nil} + fields[ImageBase] = FieldInfo{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} + fields[ImageChecksum] = FieldInfo{ImageChecksum, "image checksum", params.Uint32, []string{"image.checksum = 746424"}, &Deprecation{Since: "3.0.0", Fields: []Field{ModuleChecksum}}, nil} + fields[ImageSize] = FieldInfo{ImageSize, "image size", params.Uint32, []string{"image.size > 1024"}, &Deprecation{Since: "3.0.0", Fields: []Field{ModuleSize}}, nil} + fields[ImageDefaultAddress] = FieldInfo{ImageDefaultAddress, "default image address", params.Address, []string{"image.default.address = '7efe0000'"}, &Deprecation{Since: "3.0.0", Fields: []Field{ModuleDefaultAddress}}, nil} + fields[ImagePID] = FieldInfo{ImagePID, "target process identifier", params.Uint32, []string{"image.pid = 80"}, &Deprecation{Since: "3.0.0", Fields: []Field{ModulePID}}, nil} + fields[ImageSignatureType] = FieldInfo{ImageSignatureType, "image signature type", params.AnsiString, []string{"image.signature.type != 'NONE'"}, &Deprecation{Since: "3.0.0", Fields: []Field{ModuleSignatureType}}, nil} + fields[ImageSignatureLevel] = FieldInfo{ImageSignatureLevel, "image signature level", params.AnsiString, []string{"image.signature.level = 'AUTHENTICODE'"}, &Deprecation{Since: "3.0.0", Fields: []Field{ModuleSignatureLevel}}, nil} + fields[ImageCertSerial] = FieldInfo{ImageCertSerial, "image certificate serial number", params.UnicodeString, []string{"image.cert.serial = '330000023241fb59996dcc4dff000000000232'"}, &Deprecation{Since: "3.0.0", Fields: []Field{ModuleSignatureSerial}}, nil} + fields[ImageCertSubject] = FieldInfo{ImageCertSubject, "image certificate subject", params.UnicodeString, []string{"image.cert.subject contains 'Washington, Redmond, Microsoft Corporation'"}, &Deprecation{Since: "3.0.0", Fields: []Field{ModuleSignatureSubject}}, nil} + fields[ImageCertIssuer] = FieldInfo{ImageCertIssuer, "image certificate CA", params.UnicodeString, []string{"image.cert.issuer contains 'Washington, Redmond, Microsoft Corporation'"}, &Deprecation{Since: "3.0.0", Fields: []Field{ModuleSignatureIssuer}}, nil} + fields[ImageCertAfter] = FieldInfo{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} + fields[ImageCertBefore] = FieldInfo{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} + fields[ImageIsDLL] = FieldInfo{ImageIsDLL, "indicates if the loaded image is a DLL", params.Bool, []string{"image.is_dll'"}, &Deprecation{Since: "3.0.0", Fields: []Field{ModuleIsDLL}}, nil} + fields[ImageIsDriver] = FieldInfo{ImageIsDriver, "indicates if the loaded image is a driver", params.Bool, []string{"image.is_driver'"}, &Deprecation{Since: "3.0.0", Fields: []Field{ModuleIsDriver}}, nil} + fields[ImageIsExecutable] = FieldInfo{ImageIsExecutable, "indicates if the loaded image is an executable", params.Bool, []string{"image.is_exec'"}, &Deprecation{Since: "3.0.0", Fields: []Field{ModuleIsExecutable}}, nil} + fields[ImageIsDotnet] = FieldInfo{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} + fields[ModulePath] = FieldInfo{ModulePath, "full module path", params.UnicodeString, []string{"module.path = 'C:\\Windows\\System32\\advapi32.dll'"}, nil, nil} + fields[ModulePathStem] = FieldInfo{ModulePathStem, "module path stem", params.UnicodeString, []string{"module.path.stem = 'C:\\Windows\\System32\\advapi32'"}, nil, nil} + fields[ModuleName] = FieldInfo{ModuleName, "module name", params.UnicodeString, []string{"module.name = 'advapi32.dll'"}, nil, nil} + fields[ModuleBase] = FieldInfo{ModuleBase, "the base address of process in which the module is loaded", params.Address, []string{"module.base.address = 'a65d800000'"}, nil, nil} + fields[ModuleChecksum] = FieldInfo{ModuleChecksum, "module checksum", params.Uint32, []string{"module.checksum = 746424"}, nil, nil} + fields[ModuleSize] = FieldInfo{ModuleSize, "module size", params.Uint32, []string{"module.size > 1024"}, nil, nil} + fields[ModuleDefaultAddress] = FieldInfo{ModuleDefaultAddress, "default module address", params.Address, []string{"module.default_address = '7efe0000'"}, nil, nil} + fields[ModulePID] = FieldInfo{ModulePID, "target process identifier", params.Uint32, []string{"module.pid = 80"}, nil, nil} + fields[ModuleSignatureType] = FieldInfo{ModuleSignatureType, "module signature type", params.AnsiString, []string{"module.signature.type != 'NONE'"}, nil, nil} + fields[ModuleSignatureLevel] = FieldInfo{ModuleSignatureLevel, "module signature level", params.AnsiString, []string{"module.signature.level = 'AUTHENTICODE'"}, nil, nil} + fields[ModuleSignatureExists] = FieldInfo{ModuleSignatureExists, "indicates if the module is signed", params.Bool, []string{"module.signature.exists = true"}, nil, nil} + fields[ModuleSignatureTrusted] = FieldInfo{ModuleSignatureTrusted, "indicates if the module signature is trusted", params.Bool, []string{"module.signature.trusted = false"}, nil, nil} + fields[ModuleSignatureSerial] = FieldInfo{ModuleSignatureSerial, "module certificate serial number", params.UnicodeString, []string{"module.signature.serial = '330000023241fb59996dcc4dff000000000232'"}, nil, nil} + fields[ModuleSignatureSubject] = FieldInfo{ModuleSignatureSubject, "module certificate subject", params.UnicodeString, []string{"module.signature.subject contains 'Washington, Redmond, Microsoft Corporation'"}, nil, nil} + fields[ModuleSignatureIssuer] = FieldInfo{ModuleSignatureIssuer, "module certificate CA", params.UnicodeString, []string{"module.signature.issuer contains 'Washington, Redmond, Microsoft Corporation'"}, nil, nil} + fields[ModuleSignatureAfter] = FieldInfo{ModuleSignatureAfter, "module certificate expiration date", params.Time, []string{"module.signature.after contains '2024-02-01 00:05:42 +0000 UTC'"}, nil, nil} + fields[ModuleSignatureBefore] = FieldInfo{ModuleSignatureBefore, "module certificate enrollment date", params.Time, []string{"module.signature.before contains '2024-02-01 00:05:42 +0000 UTC'"}, nil, nil} + fields[ModuleIsDLL] = FieldInfo{ModuleIsDLL, "indicates if the loaded module is a DLL", params.Bool, []string{"module.is_dll'"}, nil, nil} + fields[ModuleIsDriver] = FieldInfo{ModuleIsDriver, "indicates if the loaded module is a driver", params.Bool, []string{"module.is_driver'"}, nil, nil} + fields[ModuleIsExecutable] = FieldInfo{ModuleIsExecutable, "indicates if the loaded module is an executable", params.Bool, []string{"module.is_exec'"}, nil, nil} + fields[ModuleIsDotnet] = FieldInfo{ModuleIsDotnet, "indicates if the loaded module is a .NET assembly", params.Bool, []string{"module.pe.is_dotnet'"}, nil, nil} + fields[DllPath] = FieldInfo{DllPath, "full dll path", params.UnicodeString, []string{"dll.path = 'C:\\Windows\\System32\\advapi32.dll'"}, nil, nil} + fields[DllPathStem] = FieldInfo{DllPathStem, "dll path stem", params.UnicodeString, []string{"dll.path.stem = 'C:\\Windows\\System32\\advapi32'"}, nil, nil} + fields[DllName] = FieldInfo{DllName, "module name", params.UnicodeString, []string{"dll.name = 'advapi32.dll'"}, nil, nil} + fields[DllBase] = FieldInfo{DllBase, "the base address of process in which the DLL is loaded", params.Address, []string{"dll.base = 'a65d800000'"}, nil, nil} + fields[DllSize] = FieldInfo{DllSize, "dll virtual mapped size", params.Uint32, []string{"dll.size > 1024"}, nil, nil} + fields[DllPID] = FieldInfo{DllPID, "target process identifier", params.Uint32, []string{"dll.pid = 80"}, nil, nil} + fields[DllSignatureType] = FieldInfo{DllSignatureType, "dll signature type", params.AnsiString, []string{"dll.signature.type != 'NONE'"}, nil, nil} + fields[DllSignatureLevel] = FieldInfo{DllSignatureLevel, "dll signature level", params.AnsiString, []string{"dll.signature.level = 'AUTHENTICODE'"}, nil, nil} + fields[DllSignatureExists] = FieldInfo{DllSignatureExists, "indicates if the dll is signed", params.Bool, []string{"dll.signature.exists = true"}, nil, nil} + fields[DllSignatureTrusted] = FieldInfo{DllSignatureTrusted, "indicates if the dll signature is trusted", params.Bool, []string{"dll.signature.trusted = false"}, nil, nil} + fields[DllSignatureSerial] = FieldInfo{DllSignatureSerial, "dll certificate serial number", params.UnicodeString, []string{"dll.signature.serial = '330000023241fb59996dcc4dff000000000232'"}, nil, nil} + fields[DllSignatureSubject] = FieldInfo{DllSignatureSubject, "dll certificate subject", params.UnicodeString, []string{"dll.signature.subject contains 'Washington, Redmond, Microsoft Corporation'"}, nil, nil} + fields[DllSignatureIssuer] = FieldInfo{DllSignatureIssuer, "dll certificate CA", params.UnicodeString, []string{"dll.signature.issuer contains 'Washington, Redmond, Microsoft Corporation'"}, nil, nil} + fields[DllSignatureAfter] = FieldInfo{DllSignatureAfter, "moddllule certificate expiration date", params.Time, []string{"dll.signature.after contains '2024-02-01 00:05:42 +0000 UTC'"}, nil, nil} + fields[DllSignatureBefore] = FieldInfo{DllSignatureBefore, "dll certificate enrollment date", params.Time, []string{"dll.signature.before contains '2024-02-01 00:05:42 +0000 UTC'"}, nil, nil} + fields[DllIsDotnet] = FieldInfo{DllIsDotnet, "indicates if the loaded dll is a .NET assembly", params.Bool, []string{"dll.pe.is_dotnet'"}, nil, nil} + fields[FileObject] = FieldInfo{FileObject, "file object address", params.Uint64, []string{"file.object = 18446738026482168384"}, nil, nil} + fields[FilePath] = FieldInfo{FilePath, "full file path", params.UnicodeString, []string{"file.path = 'C:\\Windows\\System32'"}, nil, nil} + fields[FilePathStem] = FieldInfo{FilePathStem, "full file path without extension", params.UnicodeString, []string{"file.path.stem = 'C:\\Windows\\System32\\cmd'"}, nil, nil} + fields[FileName] = FieldInfo{FileName, "full file name", params.UnicodeString, []string{"file.name contains 'mimikatz'"}, nil, nil} + fields[FileOperation] = FieldInfo{FileOperation, "file operation", params.AnsiString, []string{"file.operation = 'open'"}, nil, nil} + fields[FileShareMask] = FieldInfo{FileShareMask, "file share mask", params.AnsiString, []string{"file.share.mask = 'READ'"}, &Deprecation{Since: "3.1.0", Fields: []Field{FileShareMode}}, nil} + fields[FileShareMode] = FieldInfo{FileShareMask, "file share mode", params.AnsiString, []string{"file.share_mode = 'DENY'"}, nil, nil} + fields[FileIOSize] = FieldInfo{FileIOSize, "file I/O size", params.Uint32, []string{"file.io.size > 512"}, nil, nil} + fields[FileOffset] = FieldInfo{FileOffset, "file offset", params.Uint64, []string{"file.offset = 1024"}, nil, nil} + fields[FileType] = FieldInfo{FileType, "file type", params.AnsiString, []string{"file.type = 'directory'"}, nil, nil} + fields[FileExtension] = FieldInfo{FileExtension, "file extension", params.AnsiString, []string{"file.extension = '.dll'"}, nil, nil} + fields[FileAttributes] = FieldInfo{FileAttributes, "file attributes", params.Slice, []string{"file.attributes in ('archive', 'hidden')"}, nil, nil} + fields[FileStatus] = FieldInfo{FileStatus, "file operation status message", params.UnicodeString, []string{"file.status != 'success'"}, nil, nil} + fields[FileViewBase] = FieldInfo{FileViewBase, "view base address", params.Address, []string{"file.view.base = '25d42170000'"}, nil, nil} + fields[FileViewSize] = FieldInfo{FileViewSize, "size of the mapped view", params.Uint64, []string{"file.view.size > 1024"}, nil, nil} + fields[FileViewType] = FieldInfo{FileViewType, "type of the mapped view section", params.Enum, []string{"file.view.type = 'IMAGE'"}, nil, nil} + fields[FileViewProtection] = FieldInfo{FileViewProtection, "protection rights of the section view", params.AnsiString, []string{"file.view.protection = 'READONLY'"}, nil, nil} + fields[FileIsDLL] = FieldInfo{FileIsDLL, "indicates if the created file is a DLL", params.Bool, []string{"file.is_dll'"}, nil, nil} + fields[FileIsDriver] = FieldInfo{FileIsDriver, "indicates if the created file is a driver", params.Bool, []string{"file.is_driver'"}, nil, nil} + fields[FileIsExecutable] = FieldInfo{FileIsExecutable, "indicates if the created file is an executable", params.Bool, []string{"file.is_exec'"}, nil, nil} + fields[FilePID] = FieldInfo{FilePID, "denotes the process id performing file operation", params.PID, []string{"file.pid = 4"}, nil, nil} + fields[FileKey] = FieldInfo{FileKey, "uniquely identifies the file object", params.Uint64, []string{"file.key = 12446738026482168384"}, nil, nil} + fields[FileInfoClass] = FieldInfo{FileInfoClass, "identifies the file information class", params.Enum, []string{"file.info_class = 'Allocation'"}, nil, nil} + fields[FileInfoAllocationSize] = FieldInfo{FileInfoAllocationSize, "file allocation size", params.Uint64, []string{"file.info.allocation_size > 645400"}, nil, nil} + fields[FileInfoEOFSize] = FieldInfo{FileInfoEOFSize, "file EOF size", params.Uint64, []string{"file.info.eof_size > 1000"}, nil, nil} + fields[FileInfoIsDispositionDeleteFile] = FieldInfo{FileInfoIsDispositionDeleteFile, "indicates if the file is deleted when its handle is closed", params.Bool, []string{"file.info.is_disposition_file_delete = true"}, nil, nil} + fields[RegistryPath] = FieldInfo{RegistryPath, "fully qualified registry path", params.UnicodeString, []string{"registry.path = 'HKEY_LOCAL_MACHINE\\SYSTEM'"}, nil, nil} + fields[RegistryKeyName] = FieldInfo{RegistryKeyName, "registry key name", params.UnicodeString, []string{"registry.key.name = 'CurrentControlSet'"}, nil, nil} + fields[RegistryKCB] = FieldInfo{RegistryKCB, "registry KCB address", params.Address, []string{"registry.kcb = 'FFFFB905D60C2268'"}, nil, nil} + fields[RegistryValue] = FieldInfo{RegistryValue, "registry value name", params.UnicodeString, []string{"registry.value = 'Epoch'"}, nil, nil} + fields[RegistryValueType] = FieldInfo{RegistryValueType, "type of registry value", params.UnicodeString, []string{"registry.value.type = 'REG_SZ'"}, nil, nil} + fields[RegistryData] = FieldInfo{RegistryData, "registry value captured data", params.Object, []string{"registry.data = '%SystemRoot%'"}, nil, nil} + fields[RegistryStatus] = FieldInfo{RegistryStatus, "status of registry operation", params.UnicodeString, []string{"registry.status != 'success'"}, nil, nil} + fields[NetDIP] = FieldInfo{NetDIP, "destination IP address", params.IP, []string{"net.dip = 172.17.0.3"}, nil, nil} + fields[NetSIP] = FieldInfo{NetSIP, "source IP address", params.IP, []string{"net.sip = 127.0.0.1"}, nil, nil} + fields[NetDport] = FieldInfo{NetDport, "destination port", params.Uint16, []string{"net.dport in (80, 443, 8080)"}, nil, nil} + fields[NetSport] = FieldInfo{NetSport, "source port", params.Uint16, []string{"net.sport != 3306"}, nil, nil} + fields[NetDportName] = FieldInfo{NetDportName, "destination port name", params.AnsiString, []string{"net.dport.name = 'dns'"}, nil, nil} + fields[NetSportName] = FieldInfo{NetSportName, "source port name", params.AnsiString, []string{"net.sport.name = 'http'"}, nil, nil} + fields[NetL4Proto] = FieldInfo{NetL4Proto, "layer 4 protocol name", params.AnsiString, []string{"net.l4.proto = 'TCP"}, nil, nil} + fields[NetPacketSize] = FieldInfo{NetPacketSize, "packet size", params.Uint32, []string{"net.size > 512"}, nil, nil} + fields[NetSIPNames] = FieldInfo{NetSIPNames, "source IP names", params.Slice, []string{"net.sip.names in ('github.com.')"}, nil, nil} + fields[NetDIPNames] = FieldInfo{NetDIPNames, "destination IP names", params.Slice, []string{"net.dip.names in ('github.com.')"}, nil, nil} + fields[PeNumSections] = FieldInfo{PeNumSections, "number of sections", params.Uint16, []string{"pe.nsections < 5"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsPeNumSections}}, nil} + fields[PeNumSymbols] = FieldInfo{PeNumSymbols, "number of entries in the symbol table", params.Uint32, []string{"pe.nsymbols > 230"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsPeNumSymbols}}, nil} + fields[PeBaseAddress] = FieldInfo{PeBaseAddress, "image base address", params.Address, []string{"pe.address.base = '140000000'"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsPeBaseAddress}}, nil} + fields[PeEntrypoint] = FieldInfo{PeEntrypoint, "address of the entrypoint function", params.Address, []string{"pe.address.entrypoint = '20110'"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsPeEntrypoint}}, nil} + fields[PeSymbols] = FieldInfo{PeSymbols, "imported symbols", params.Slice, []string{"pe.symbols in ('GetTextFaceW', 'GetProcessHeap')"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsPeSymbols}}, nil} + fields[PeImports] = FieldInfo{PeImports, "imported dynamic linked libraries", params.Slice, []string{"pe.imports in ('msvcrt.dll', 'GDI32.dll'"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsPeImports}}, nil} + fields[PeResources] = FieldInfo{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 + }}} + fields[PeCompany] = FieldInfo{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} + fields[PeCopyright] = FieldInfo{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} + fields[PeDescription] = FieldInfo{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} + fields[PeFileName] = FieldInfo{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} + fields[PeFileVersion] = FieldInfo{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} + fields[PeProduct] = FieldInfo{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} + fields[PeProductVersion] = FieldInfo{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} + fields[PeIsDLL] = FieldInfo{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} + fields[PeIsDriver] = FieldInfo{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} + fields[PeIsExecutable] = FieldInfo{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} + fields[PeImphash] = FieldInfo{PeImphash, "import hash", params.AnsiString, []string{"pe.impash = '5d3861c5c547f8a34e471ba273a732b2'"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsPeImphash}}, nil} + fields[PeIsDotnet] = FieldInfo{PeIsDotnet, "indicates if PE contains CLR data", params.Bool, []string{"pe.is_dotnet"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsPeIsDotnet}}, nil} + fields[PeAnomalies] = FieldInfo{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} + fields[PeIsSigned] = FieldInfo{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} + fields[PeIsTrusted] = FieldInfo{PeIsTrusted, "indicates if the PE certificate chain is trusted", params.Bool, []string{"pe.is_trusted"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsSignatureTrusted}}, nil} + fields[PeCertSerial] = FieldInfo{PeCertSerial, "PE certificate serial number", params.UnicodeString, []string{"pe.cert.serial = '330000023241fb59996dcc4dff000000000232'"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsSignatureSerial}}, nil} + fields[PeCertSubject] = FieldInfo{PeCertSubject, "PE certificate subject", params.UnicodeString, []string{"pe.cert.subject contains 'Washington, Redmond, Microsoft Corporation'"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsSignatureSubject}}, nil} + fields[PeCertIssuer] = FieldInfo{PeCertIssuer, "PE certificate CA", params.UnicodeString, []string{"pe.cert.issuer contains 'Washington, Redmond, Microsoft Corporation'"}, &Deprecation{Since: "3.0.0", Fields: []Field{PsSignatureIssuer}}, nil} + fields[PeCertAfter] = FieldInfo{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} + fields[PeCertBefore] = FieldInfo{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} + fields[PeIsModified] = FieldInfo{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} + fields[MemBaseAddress] = FieldInfo{MemBaseAddress, "region base address", params.Address, []string{"mem.address = '211d13f2000'"}, nil, nil} + fields[MemRegionSize] = FieldInfo{MemRegionSize, "region size", params.Uint64, []string{"mem.size > 438272"}, nil, nil} + fields[MemAllocType] = FieldInfo{MemAllocType, "region allocation or release type", params.Flags, []string{"mem.alloc = 'COMMIT'"}, nil, nil} + fields[MemPageType] = FieldInfo{MemPageType, "page type of the allocated region", params.Enum, []string{"mem.type = 'PRIVATE'"}, nil, nil} + fields[MemProtection] = FieldInfo{MemProtection, "allocated region protection type", params.Enum, []string{"mem.protection = 'READWRITE'"}, nil, nil} + fields[MemProtectionMask] = FieldInfo{MemProtectionMask, "allocated region protection in mask notation", params.Enum, []string{"mem.protection.mask = 'RWX'"}, nil, nil} + fields[DNSName] = FieldInfo{DNSName, "dns query name", params.UnicodeString, []string{"dns.name = 'example.org'"}, nil, nil} + fields[DNSRR] = FieldInfo{DNSRR, "dns resource record type", params.AnsiString, []string{"dns.rr = 'AA'"}, nil, nil} + fields[DNSOptions] = FieldInfo{DNSOptions, "dns query options", params.Flags64, []string{"dns.options in ('ADDRCONFIG', 'DUAL_ADDR')"}, nil, nil} + fields[DNSRcode] = FieldInfo{DNSRR, "dns response status", params.AnsiString, []string{"dns.rcode = 'NXDOMAIN'"}, nil, nil} + fields[DNSAnswers] = FieldInfo{DNSAnswers, "dns response answers", params.Slice, []string{"dns.answers in ('o.lencr.edgesuite.net', 'a1887.dscq.akamai.net')"}, nil, nil} +} diff --git a/pkg/filter/fields/fields.go b/pkg/filter/fields/fields.go index 56c920a89..272a32a12 100644 --- a/pkg/filter/fields/fields.go +++ b/pkg/filter/fields/fields.go @@ -21,7 +21,6 @@ package fields import ( "github.com/rabbitstack/fibratus/pkg/event/params" "sort" - "unicode" ) // FieldInfo is the field metadata descriptor. @@ -34,17 +33,6 @@ type FieldInfo struct { Argument *Argument } -// isNumber is the field argument validation function that -// returns true if all characters are digits. -var isNumber = func(s string) bool { - for _, c := range s { - if !unicode.IsNumber(c) { - return false - } - } - return true -} - // Argument defines field argument information. type Argument struct { // Optional indicates if the argument is optional. diff --git a/pkg/filter/fields/fields_windows.go b/pkg/filter/fields/fields_windows.go deleted file mode 100644 index 155eaa2e9..000000000 --- a/pkg/filter/fields/fields_windows.go +++ /dev/null @@ -1,1238 +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" - - // 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" -) - -// 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) 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) 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}, - - 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}, -} - -// 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.go b/pkg/filter/filter.go index 95add0fd4..5c33d628e 100644 --- a/pkg/filter/filter.go +++ b/pkg/filter/filter.go @@ -22,7 +22,6 @@ import ( "errors" "expvar" "fmt" - "reflect" "regexp" "strconv" "strings" @@ -101,44 +100,6 @@ type BoundField struct { accessor Accessor } -// Accessor finds exactly one accessor that can serve the bound field. -func (b *BoundField) Accessor(f *filter) Accessor { - if b.accessor != nil { - return b.accessor - } - switch { - case b.Field.Name.IsKevtField(), b.Field.Name.IsEvtField(): - b.accessor = newEventAccessor() - case b.Field.Name.IsPsField(): - for _, accessor := range f.accessors { - if reflect.TypeOf(accessor) == reflect.TypeOf(&psAccessor{}) { - b.accessor = accessor - break - } - } - if b.accessor == nil { - b.accessor = newPSAccessor(nil) - } - case b.Field.Name.IsThreadField(): - b.accessor = newThreadAccessor() - case b.Field.Name.IsImageField(): - b.accessor = newModuleAccessor() - case b.Field.Name.IsFileField(): - b.accessor = newFileAccessor() - case b.Field.Name.IsRegistryField(): - b.accessor = newRegistryAccessor() - case b.Field.Name.IsNetworkField(): - b.accessor = newNetworkAccessor() - case b.Field.Name.IsPeField(): - b.accessor = newPEAccessor() - case b.Field.Name.IsMemField(): - b.accessor = newMemAccessor() - case b.Field.Name.IsDNSField(): - b.accessor = newDNSAccessor() - } - return b.accessor -} - type filter struct { expr ql.Expr seq *ql.Sequence diff --git a/pkg/filter/filter_linux.go b/pkg/filter/filter_linux.go new file mode 100644 index 000000000..dee4a5943 --- /dev/null +++ b/pkg/filter/filter_linux.go @@ -0,0 +1,152 @@ +//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 filter + +import ( + "fmt" + "reflect" + "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.Snapshotter +} + +// 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 { + 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), + newThreadAccessor(), + } + + if config.EventSource.EnableFileIOEvents { + accessors = append(accessors, newFileAccessor()) + } + if config.EventSource.EnableNetEvents { + accessors = append(accessors, newNetworkAccessor()) + } + if config.EventSource.EnableMemEvents { + accessors = append(accessors, newMemAccessor()) + } + + 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 +} + +// Accessor finds exactly one accessor that can serve the bound field. +func (b *BoundField) Accessor(f *filter) Accessor { + if b.accessor != nil { + return b.accessor + } + switch { + case b.Field.Name.IsKevtField(), b.Field.Name.IsEvtField(): + b.accessor = newEventAccessor() + case b.Field.Name.IsPsField(): + for _, accessor := range f.accessors { + if reflect.TypeOf(accessor) == reflect.TypeOf(&psAccessor{}) { + b.accessor = accessor + break + } + } + if b.accessor == nil { + b.accessor = newPSAccessor(nil) + } + case b.Field.Name.IsThreadField(): + b.accessor = newThreadAccessor() + case b.Field.Name.IsFileField(): + b.accessor = newFileAccessor() + case b.Field.Name.IsNetworkField(): + b.accessor = newNetworkAccessor() + case b.Field.Name.IsMemField(): + b.accessor = newMemAccessor() + } + return b.accessor +} diff --git a/pkg/filter/filter_linux_test.go b/pkg/filter/filter_linux_test.go new file mode 100644 index 000000000..4370c5e76 --- /dev/null +++ b/pkg/filter/filter_linux_test.go @@ -0,0 +1,614 @@ +//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 filter + +import ( + "net" + "testing" + + "github.com/rabbitstack/fibratus/pkg/config" + "github.com/rabbitstack/fibratus/pkg/event" + "github.com/rabbitstack/fibratus/pkg/event/params" + "github.com/rabbitstack/fibratus/pkg/filter/fields" + pstypes "github.com/rabbitstack/fibratus/pkg/ps/types" + "github.com/stretchr/testify/require" +) + +var cfg = &config.Config{ + EventSource: config.EventSourceConfig{ + EnableFileIOEvents: true, + EnableNetEvents: true, + EnableMemEvents: true, + }, + Filters: &config.Filters{}, +} + +func evalFilter(t *testing.T, expr string, evt *event.Event) bool { + t.Helper() + f := New(expr, cfg) + require.NoError(t, f.Compile(), expr) + return f.Eval(evt) +} + +func testPS() *pstypes.PS { + parent := &pstypes.PS{ + PID: 1, + Name: "systemd", + Cmdline: "/sbin/init", + Exe: "/sbin/init", + Cwd: "/", + Args: []string{"/sbin/init"}, + Username: "root", + UID: 0, + GID: 0, + StartBootTime: 100, + Envs: map[string]string{"PATH": "/usr/sbin"}, + } + return &pstypes.PS{ + PID: 4242, + Ppid: 1, + Name: "bash", + Cmdline: "/bin/bash -lc test", + Exe: "/bin/bash", + Cwd: "/home/user", + Args: []string{"-lc", "test"}, + Username: "user", + UID: 1000, + GID: 1000, + StartBootTime: 200, + Envs: map[string]string{"HOME": "/home/user", "PATH": "/usr/bin"}, + Parent: parent, + } +} + +func TestFilterCompile(t *testing.T) { + f := New(`ps.name = 'bash'`, cfg) + require.NoError(t, f.Compile()) + f = New(`'bash'`, cfg) + require.EqualError(t, f.Compile(), "expected at least one field or operator but zero found") + f = New(`ps.name`, cfg) + require.EqualError(t, f.Compile(), "expected at least one field or operator but zero found") + f = New(`file.path = '/tmp/x'`, cfg) + require.NoError(t, f.Compile()) + f = New(`net.dport = 443`, cfg) + require.NoError(t, f.Compile()) + f = New(`mem.size > 4096`, cfg) + require.NoError(t, f.Compile()) + f = New(`ps.name =`, cfg) + require.Error(t, f.Compile()) +} + +func TestWindowsOnlyFieldsUnavailable(t *testing.T) { + exprs := []string{ + `kevt.pid = 1`, + `kevt.name = 'execve'`, + `kevt.arg[exe] = '/bin/bash'`, + `ps.sid = 'S-1-5-18'`, + `registry.path = 'HKLM'`, + `pe.address.entrypoint = '20110'`, + `file.object = 1`, + `mem.type = 'PRIVATE'`, + `mem.alloc = 'COMMIT'`, + `handle.name = 'mutant'`, + `dns.name = 'example.org'`, + `evt.is_direct_syscall = true`, + `evt.truncated = true`, + `file.truncated = true`, + `file.new_path = '/tmp/x'`, + `net.path = '/tmp/app.sock'`, + `ps.clone.flags = 0`, + `evt.syscall = 59`, + `mem.flags = 1`, + `mem.fd = 3`, + `mem.offset = 0`, + } + for _, expr := range exprs { + f := New(expr, cfg) + require.Error(t, f.Compile(), expr) + } +} + +func TestSharedFieldSemantics(t *testing.T) { + ps := testPS() + openat := &event.Event{ + Type: event.Openat, + Category: event.File, + Name: "openat", + PID: 4242, + Tid: 4242, + PS: ps, + Params: event.Params{ + params.FilePath: {Name: params.FilePath, Type: params.Path, Value: "/tmp/secret.txt"}, + }, + } + connect := &event.Event{ + Type: event.Connect, + Category: event.Net, + Name: "connect", + PID: 4242, + PS: ps, + Params: event.Params{ + params.NetDIP: {Name: params.NetDIP, Type: params.IPv4, Value: net.IPv4(1, 2, 3, 4).To4()}, + params.NetDport: {Name: params.NetDport, Type: params.Port, Value: uint16(443)}, + }, + } + mmap := &event.Event{ + Type: event.Mmap, + Category: event.Mem, + Name: "mmap", + PID: 4242, + PS: ps, + Params: event.Params{ + params.MemBaseAddress: {Name: params.MemBaseAddress, Type: params.Address, Value: uint64(8192)}, + params.MemRegionSize: {Name: params.MemRegionSize, Type: params.Uint64, Value: uint64(4096)}, + params.MemProtect: {Name: params.MemProtect, Type: params.Uint32, Value: uint32(3)}, + }, + } + + require.True(t, evalFilter(t, `ps.name = 'bash'`, openat)) + require.True(t, evalFilter(t, `ps.exe = '/bin/bash'`, openat)) + require.True(t, evalFilter(t, `ps.cmdline contains 'bash'`, openat)) + require.True(t, evalFilter(t, `ps.uuid > 0`, openat)) + require.True(t, evalFilter(t, `file.path = '/tmp/secret.txt'`, openat)) + require.True(t, evalFilter(t, `file.name = 'secret.txt'`, openat)) + require.True(t, evalFilter(t, `file.extension = '.txt'`, openat)) + require.True(t, evalFilter(t, `file.path.stem = '/tmp/secret'`, openat)) + require.True(t, evalFilter(t, `net.dip = 1.2.3.4`, connect)) + require.True(t, evalFilter(t, `net.dport = 443`, connect)) + require.True(t, evalFilter(t, `mem.address = 8192`, mmap)) + require.True(t, evalFilter(t, `mem.size = 4096`, mmap)) + require.True(t, evalFilter(t, `mem.protection = 3`, mmap)) +} + +func TestProcFilter(t *testing.T) { + ps := testPS() + execve := &event.Event{ + Type: event.Execve, + Category: event.Process, + Name: "execve", + PID: 4242, + Tid: 4242, + CPU: 2, + PS: ps, + Params: event.Params{ + params.Retval: {Name: params.Retval, Type: params.Int64, Value: int64(0)}, + params.SyscallID: {Name: params.SyscallID, Type: params.Uint32, Value: uint32(59)}, + params.UID: {Name: params.UID, Type: params.Uint32, Value: uint32(1000)}, + params.GID: {Name: params.GID, Type: params.Uint32, Value: uint32(1000)}, + params.Exe: {Name: params.Exe, Type: params.Path, Value: "/bin/bash"}, + }, + } + kill := &event.Event{ + Type: event.Kill, + Category: event.Process, + Name: "kill", + PID: 4242, + PS: ps, + Params: event.Params{ + params.TargetProcessID: {Name: params.TargetProcessID, Type: params.Int64, Value: int64(99)}, + params.Signal: {Name: params.Signal, Type: params.Int32, Value: int32(9)}, + params.Retval: {Name: params.Retval, Type: params.Int64, Value: int64(0)}, + }, + } + // kill accepts a pid_t whose sign selects the scope of the signal + broadcastKill := &event.Event{ + Type: event.Kill, + Category: event.Process, + Name: "kill", + PID: 4242, + PS: ps, + Params: event.Params{ + params.TargetProcessID: {Name: params.TargetProcessID, Type: params.Int64, Value: int64(-1)}, + params.Signal: {Name: params.Signal, Type: params.Int32, Value: int32(9)}, + }, + } + groupKill := &event.Event{ + Type: event.Kill, + Category: event.Process, + Name: "kill", + PID: 4242, + PS: ps, + Params: event.Params{ + params.TargetProcessID: {Name: params.TargetProcessID, Type: params.Int64, Value: int64(-4242)}, + params.Signal: {Name: params.Signal, Type: params.Int32, Value: int32(9)}, + }, + } + ptrace := &event.Event{ + Type: event.Ptrace, + Category: event.Process, + Name: "ptrace", + PID: 4242, + PS: ps, + Params: event.Params{ + params.PtraceRequest: {Name: params.PtraceRequest, Type: params.Int64, Value: int64(16)}, + params.TargetProcessID: {Name: params.TargetProcessID, Type: params.Int64, Value: int64(99)}, + }, + } + prctl := &event.Event{ + Type: event.Prctl, + Category: event.Process, + Name: "prctl", + PID: 4242, + PS: ps, + Params: event.Params{ + params.PrctlOption: {Name: params.PrctlOption, Type: params.Int64, Value: int64(15)}, + }, + } + clone := &event.Event{ + Type: event.Clone, + Category: event.Process, + Name: "clone", + PID: 4242, + PS: ps, + Params: event.Params{ + params.CloneFlags: {Name: params.CloneFlags, Type: params.Uint64, Value: uint64(0)}, + }, + } + + tests := []struct { + evt *event.Event + filter string + want bool + }{ + {execve, `ps.name = 'bash'`, true}, + {execve, `ps.name = 'zsh'`, false}, + {execve, `ps.pid = 4242`, true}, + {execve, `ps.ppid = 1`, true}, + {execve, `ps.parent.pid = 1`, true}, + {execve, `ps.parent.name = 'systemd'`, true}, + {execve, `ps.parent.args in ('/sbin/init')`, true}, + {execve, `ps.parent.cwd = '/'`, true}, + {execve, `ps.parent.username = 'root'`, true}, + {execve, `ps.uid = 1000`, true}, + {execve, `ps.gid = 1000`, true}, + {execve, `ps.username = 'user'`, true}, + {execve, `ps.args in ('-lc', 'test')`, true}, + {execve, `ps.envs[HOME] = '/home/user'`, true}, + {execve, `ps.envs[HO] = '/home/user'`, true}, + {execve, `ps.uuid > 0`, true}, + {execve, `ps.parent.uuid > 0`, true}, + {execve, `evt.name = 'execve'`, true}, + {execve, `evt.pid = 4242`, true}, + {execve, `evt.tid = 4242`, true}, + {execve, `evt.cpu = 2`, true}, + {execve, `evt.retval = 0`, true}, + {execve, `evt.syscall_id = 59`, true}, + {execve, `evt.arg[exe] = '/bin/bash'`, true}, + {kill, `ps.signal = 9`, true}, + {kill, `ps.target.pid = 99`, true}, + {kill, `ps.target.pid > 0`, true}, + {kill, `ps.target.pid < 0`, false}, + {broadcastKill, `ps.target.pid < 0`, true}, + {broadcastKill, `ps.target.pid > 0`, false}, + {groupKill, `ps.target.pid < 0`, true}, + {ptrace, `ps.ptrace.request = 16`, true}, + {ptrace, `ps.target.pid = 99`, true}, + {prctl, `ps.prctl.option = 15`, true}, + {clone, `ps.clone_flags = 0`, true}, + } + for i, tt := range tests { + got := evalFilter(t, tt.filter, tt.evt) + if got != tt.want { + t.Errorf("%d. %q mismatch: exp=%t got=%t", i, tt.filter, tt.want, got) + } + } +} + +func TestFileFilter(t *testing.T) { + openat := &event.Event{ + Type: event.Openat, + Category: event.File, + Name: "openat", + PID: 4242, + Params: event.Params{ + params.FilePath: {Name: params.FilePath, Type: params.Path, Value: "/etc/passwd"}, + params.DirFD: {Name: params.DirFD, Type: params.Int64, Value: int64(-100)}, + params.FileFlags: {Name: params.FileFlags, Type: params.Uint64, Value: uint64(0)}, + params.FileMode: {Name: params.FileMode, Type: params.Uint64, Value: uint64(420)}, + params.FD: {Name: params.FD, Type: params.Int64, Value: int64(3)}, + params.Retval: {Name: params.Retval, Type: params.Int64, Value: int64(3)}, + }, + } + rename := &event.Event{ + Type: event.Rename, + Category: event.File, + Name: "rename", + PID: 4242, + Params: event.Params{ + params.FilePath: {Name: params.FilePath, Type: params.Path, Value: "/tmp/old"}, + params.FileNewPath: {Name: params.FileNewPath, Type: params.Path, Value: "/tmp/new"}, + }, + } + unlink := &event.Event{ + Type: event.Unlink, + Category: event.File, + Name: "unlink", + PID: 4242, + Params: event.Params{ + params.FilePath: {Name: params.FilePath, Type: params.Path, Value: "/tmp/gone.log"}, + }, + } + + tests := []struct { + evt *event.Event + filter string + want bool + }{ + {openat, `file.path = '/etc/passwd'`, true}, + {openat, `file.name = 'passwd'`, true}, + {openat, `file.dirfd < 0`, true}, + {openat, `file.fd = 3`, true}, + {openat, `file.flags = 0`, true}, + {openat, `file.mode = 420`, true}, + {openat, `evt.retval = 3`, true}, + {rename, `file.path.target = '/tmp/new'`, true}, + {rename, `file.path = '/tmp/old'`, true}, + {unlink, `file.extension = '.log'`, true}, + {unlink, `file.name = 'gone.log'`, true}, + } + for i, tt := range tests { + got := evalFilter(t, tt.filter, tt.evt) + if got != tt.want { + t.Errorf("%d. %q mismatch: exp=%t got=%t", i, tt.filter, tt.want, got) + } + } +} + +func TestNetFilter(t *testing.T) { + connect := &event.Event{ + Type: event.Connect, + Category: event.Net, + Name: "connect", + PID: 4242, + Params: event.Params{ + params.FD: {Name: params.FD, Type: params.Int64, Value: int64(5)}, + params.SockFamily: {Name: params.SockFamily, Type: params.Uint16, Value: uint16(2)}, + params.NetDIP: {Name: params.NetDIP, Type: params.IPv4, Value: net.IPv4(172, 17, 0, 3).To4()}, + params.NetDport: {Name: params.NetDport, Type: params.Port, Value: uint16(443)}, + }, + } + accept := &event.Event{ + Type: event.Accept, + Category: event.Net, + Name: "accept", + PID: 4242, + Params: event.Params{ + params.FD: {Name: params.FD, Type: params.Int64, Value: int64(6)}, + params.SockFamily: {Name: params.SockFamily, Type: params.Uint16, Value: uint16(2)}, + params.NetSIP: {Name: params.NetSIP, Type: params.IPv4, Value: net.IPv4(127, 0, 0, 1).To4()}, + params.NetSport: {Name: params.NetSport, Type: params.Port, Value: uint16(80)}, + }, + } + unixc := &event.Event{ + Type: event.Connect, + Category: event.Net, + Name: "connect", + PID: 4242, + Params: event.Params{ + params.FD: {Name: params.FD, Type: params.Int64, Value: int64(7)}, + params.SockFamily: {Name: params.SockFamily, Type: params.Uint16, Value: uint16(1)}, + params.SockPath: {Name: params.SockPath, Type: params.Path, Value: "/tmp/app.sock"}, + }, + } + + require.True(t, evalFilter(t, `net.dip = 172.17.0.3`, connect)) + require.True(t, evalFilter(t, `net.dport = 443`, connect)) + require.True(t, evalFilter(t, `net.family = 2`, connect)) + require.True(t, evalFilter(t, `net.fd = 5`, connect)) + require.True(t, evalFilter(t, `net.sip = 127.0.0.1`, accept)) + require.True(t, evalFilter(t, `net.sport = 80`, accept)) + require.True(t, evalFilter(t, `net.unix_path = '/tmp/app.sock'`, unixc)) + require.True(t, evalFilter(t, `net.family = 1`, unixc)) +} + +func TestMemFilter(t *testing.T) { + mmap := &event.Event{ + Type: event.Mmap, + Category: event.Mem, + Name: "mmap", + PID: 4242, + Params: event.Params{ + params.MemBaseAddress: {Name: params.MemBaseAddress, Type: params.Address, Value: uint64(8192)}, + params.MemRegionSize: {Name: params.MemRegionSize, Type: params.Uint64, Value: uint64(8192)}, + params.MemProtect: {Name: params.MemProtect, Type: params.Uint32, Value: uint32(3)}, + params.MmapFlags: {Name: params.MmapFlags, Type: params.Uint64, Value: uint64(1)}, + params.FD: {Name: params.FD, Type: params.Int64, Value: int64(3)}, + params.MmapOffset: {Name: params.MmapOffset, Type: params.Uint64, Value: uint64(0)}, + }, + } + vmread := &event.Event{ + Type: event.ProcessVMRead, + Category: event.Mem, + Name: "process_vm_readv", + PID: 4242, + Params: event.Params{ + params.TargetProcessID: {Name: params.TargetProcessID, Type: params.Int64, Value: int64(99)}, + params.MemBaseAddress: {Name: params.MemBaseAddress, Type: params.Address, Value: uint64(4096)}, + params.MemRegionSize: {Name: params.MemRegionSize, Type: params.Uint64, Value: uint64(16)}, + }, + } + vmwrite := &event.Event{ + Type: event.ProcessVMWrite, + Category: event.Mem, + Name: "process_vm_writev", + PID: 4242, + Params: event.Params{ + params.TargetProcessID: {Name: params.TargetProcessID, Type: params.Int64, Value: int64(77)}, + params.MemBaseAddress: {Name: params.MemBaseAddress, Type: params.Address, Value: uint64(4096)}, + }, + } + + require.True(t, evalFilter(t, `mem.address = 8192`, mmap)) + require.True(t, evalFilter(t, `mem.size = 8192`, mmap)) + require.True(t, evalFilter(t, `mem.protection = 3`, mmap)) + require.True(t, evalFilter(t, `mem.mmap.flags = 1`, mmap)) + require.True(t, evalFilter(t, `mem.mmap.fd = 3`, mmap)) + require.True(t, evalFilter(t, `mem.mmap.offset = 0`, mmap)) + require.True(t, evalFilter(t, `mem.target.pid = 99`, vmread)) + require.True(t, evalFilter(t, `mem.target.pid = 77`, vmwrite)) +} + +func TestThreadFilter(t *testing.T) { + cloneThread := &event.Event{ + Type: event.Clone, + Category: event.Process, + Name: "clone", + PID: 4242, + Tid: 4243, + Params: event.Params{ + params.CloneFlags: {Name: params.CloneFlags, Type: params.Uint64, Value: uint64(0x00010000)}, + }, + } + cloneProc := &event.Event{ + Type: event.Clone, + Category: event.Process, + Name: "clone", + PID: 4242, + Tid: 4242, + Params: event.Params{ + params.CloneFlags: {Name: params.CloneFlags, Type: params.Uint64, Value: uint64(0)}, + }, + } + + require.True(t, evalFilter(t, `thread.tid = 4243`, cloneThread)) + require.True(t, evalFilter(t, `thread.pid = 4242`, cloneThread)) + require.False(t, evalFilter(t, `thread.tid = 4243`, cloneProc)) +} + +func TestDefaultAndMissingValues(t *testing.T) { + empty := &event.Event{ + Type: event.Execve, + Category: event.Process, + Name: "execve", + PID: 7, + Params: event.Params{}, + } + fileEvt := &event.Event{ + Type: event.Openat, + Category: event.File, + Name: "openat", + PID: 7, + Params: event.Params{}, + } + + require.True(t, evalFilter(t, `evt.retval = 0`, empty)) + require.True(t, evalFilter(t, `ps.signal = 0`, empty)) + require.True(t, evalFilter(t, `file.path = ''`, fileEvt)) + require.True(t, evalFilter(t, `not (file.path = '/tmp/x')`, fileEvt)) + require.True(t, evalFilter(t, `file.fd = 0`, fileEvt)) + require.True(t, evalFilter(t, `mem.size = 0`, &event.Event{Type: event.Mmap, Category: event.Mem, Name: "mmap", Params: event.Params{}})) +} + +func TestTruncatedFields(t *testing.T) { + filenameTrunc := &event.Event{ + Type: event.Openat, + Category: event.File, + Name: "openat", + Params: event.Params{ + params.FilePath: {Name: params.FilePath, Type: params.Path, Value: "/tmp/partial"}, + params.Truncated: {Name: params.Truncated, Type: params.Uint32, Value: uint32(1)}, + }, + } + auxTrunc := &event.Event{ + Type: event.Rename, + Category: event.File, + Name: "rename", + Params: event.Params{ + params.FilePath: {Name: params.FilePath, Type: params.Path, Value: "/tmp/old"}, + params.FileNewPath: {Name: params.FileNewPath, Type: params.Path, Value: "/tmp/partial-dest"}, + params.Truncated: {Name: params.Truncated, Type: params.Uint32, Value: uint32(2)}, + }, + } + + notTrunc := &event.Event{ + Type: event.Openat, + Category: event.File, + Name: "openat", + Params: event.Params{ + params.FilePath: {Name: params.FilePath, Type: params.Path, Value: "/tmp/full"}, + params.Truncated: {Name: params.Truncated, Type: params.Uint32, Value: uint32(0)}, + }, + } + + require.True(t, evalFilter(t, `evt.arg[truncated] = 1`, filenameTrunc)) + require.True(t, evalFilter(t, `evt.arg[truncated] = 2`, auxTrunc)) + require.True(t, evalFilter(t, `evt.arg[truncated] = 0`, notTrunc)) +} + +func TestEveryLinuxEventType(t *testing.T) { + ps := testPS() + cases := []struct { + evt *event.Event + filter string + }{ + {&event.Event{Type: event.Execve, Category: event.Process, Name: "execve", PS: ps, Params: event.Params{params.Retval: {Name: params.Retval, Type: params.Int64, Value: int64(0)}}}, `evt.name = 'execve' and ps.name = 'bash'`}, + {&event.Event{Type: event.Exit, Category: event.Process, Name: "exit", PS: ps, Params: event.Params{params.Retval: {Name: params.Retval, Type: params.Int64, Value: int64(0)}}}, `evt.name = 'exit' and evt.retval = 0`}, + {&event.Event{Type: event.Clone, Category: event.Process, Name: "clone", PS: ps, Params: event.Params{params.CloneFlags: {Name: params.CloneFlags, Type: params.Uint64, Value: uint64(0)}}}, `evt.name = 'clone' and ps.clone_flags = 0`}, + {&event.Event{Type: event.Openat, Category: event.File, Name: "openat", PS: ps, Params: event.Params{params.FilePath: {Name: params.FilePath, Type: params.Path, Value: "/tmp/x"}}}, `file.path = '/tmp/x'`}, + {&event.Event{Type: event.Unlink, Category: event.File, Name: "unlink", PS: ps, Params: event.Params{params.FilePath: {Name: params.FilePath, Type: params.Path, Value: "/tmp/x"}}}, `file.name = 'x'`}, + {&event.Event{Type: event.Rename, Category: event.File, Name: "rename", PS: ps, Params: event.Params{params.FileNewPath: {Name: params.FileNewPath, Type: params.Path, Value: "/tmp/y"}}}, `file.path.target = '/tmp/y'`}, + {&event.Event{Type: event.Connect, Category: event.Net, Name: "connect", PS: ps, Params: event.Params{params.NetDport: {Name: params.NetDport, Type: params.Port, Value: uint16(443)}}}, `net.dport = 443`}, + {&event.Event{Type: event.Accept, Category: event.Net, Name: "accept", PS: ps, Params: event.Params{params.NetSport: {Name: params.NetSport, Type: params.Port, Value: uint16(80)}}}, `net.sport = 80`}, + {&event.Event{Type: event.Mmap, Category: event.Mem, Name: "mmap", PS: ps, Params: event.Params{params.MemRegionSize: {Name: params.MemRegionSize, Type: params.Uint64, Value: uint64(4096)}}}, `mem.size = 4096`}, + {&event.Event{Type: event.ProcessVMRead, Category: event.Mem, Name: "process_vm_readv", PS: ps, Params: event.Params{params.TargetProcessID: {Name: params.TargetProcessID, Type: params.Int64, Value: int64(9)}}}, `mem.target.pid = 9`}, + {&event.Event{Type: event.ProcessVMWrite, Category: event.Mem, Name: "process_vm_writev", PS: ps, Params: event.Params{params.TargetProcessID: {Name: params.TargetProcessID, Type: params.Int64, Value: int64(8)}}}, `mem.target.pid = 8`}, + {&event.Event{Type: event.Kill, Category: event.Process, Name: "kill", PS: ps, Params: event.Params{params.Signal: {Name: params.Signal, Type: params.Int32, Value: int32(9)}}}, `ps.signal = 9`}, + {&event.Event{Type: event.Ptrace, Category: event.Process, Name: "ptrace", PS: ps, Params: event.Params{params.PtraceRequest: {Name: params.PtraceRequest, Type: params.Int64, Value: int64(16)}}}, `ps.ptrace.request = 16`}, + {&event.Event{Type: event.Prctl, Category: event.Process, Name: "prctl", PS: ps, Params: event.Params{params.PrctlOption: {Name: params.PrctlOption, Type: params.Int64, Value: int64(15)}}}, `ps.prctl.option = 15`}, + } + for _, tt := range cases { + require.True(t, evalFilter(t, tt.filter, tt.evt), tt.filter) + } +} + +func TestIsFieldAccessible(t *testing.T) { + fileEvt := &event.Event{Category: event.File} + netEvt := &event.Event{Category: event.Net} + memEvt := &event.Event{Category: event.Mem} + procEvt := &event.Event{Category: event.Process, PS: testPS()} + cloneThread := &event.Event{ + Type: event.Clone, + Category: event.Process, + Params: event.Params{params.CloneFlags: {Name: params.CloneFlags, Type: params.Uint64, Value: uint64(0x00010000)}}, + } + + require.True(t, newFileAccessor().IsFieldAccessible(fileEvt)) + require.False(t, newFileAccessor().IsFieldAccessible(procEvt)) + require.True(t, newNetworkAccessor().IsFieldAccessible(netEvt)) + require.True(t, newMemAccessor().IsFieldAccessible(memEvt)) + require.True(t, newPSAccessor(nil).IsFieldAccessible(procEvt)) + require.True(t, newThreadAccessor().IsFieldAccessible(cloneThread)) + require.False(t, newThreadAccessor().IsFieldAccessible(procEvt)) +} + +func TestGetAccessorsIncludesMatrix(t *testing.T) { + accessors := GetAccessors() + require.Len(t, accessors, 6) +} + +func TestFieldCatalogTypes(t *testing.T) { + require.Equal(t, params.Uint64, fields.PsUUID.Type()) + require.Equal(t, params.Uint32, fields.PsUID.Type()) + require.Equal(t, params.Int64, fields.PsSignal.Type()) + require.Equal(t, params.Uint32, fields.EvtSyscallID.Type()) + require.Equal(t, params.String, fields.FilePathTarget.Type()) +} diff --git a/pkg/filter/filter_windows.go b/pkg/filter/filter_windows.go index 3f4fadf52..4cbafd5ca 100644 --- a/pkg/filter/filter_windows.go +++ b/pkg/filter/filter_windows.go @@ -20,6 +20,7 @@ package filter import ( "fmt" + "reflect" "strings" "github.com/rabbitstack/fibratus/pkg/config" @@ -134,3 +135,41 @@ func NewFromCLIWithAllAccessors(args []string) (Filter, error) { } return filter, nil } + +// Accessor finds exactly one accessor that can serve the bound field. +func (b *BoundField) Accessor(f *filter) Accessor { + if b.accessor != nil { + return b.accessor + } + switch { + case b.Field.Name.IsKevtField(), b.Field.Name.IsEvtField(): + b.accessor = newEventAccessor() + case b.Field.Name.IsPsField(): + for _, accessor := range f.accessors { + if reflect.TypeOf(accessor) == reflect.TypeOf(&psAccessor{}) { + b.accessor = accessor + break + } + } + if b.accessor == nil { + b.accessor = newPSAccessor(nil) + } + case b.Field.Name.IsThreadField(): + b.accessor = newThreadAccessor() + case b.Field.Name.IsImageField(): + b.accessor = newModuleAccessor() + case b.Field.Name.IsFileField(): + b.accessor = newFileAccessor() + case b.Field.Name.IsRegistryField(): + b.accessor = newRegistryAccessor() + case b.Field.Name.IsNetworkField(): + b.accessor = newNetworkAccessor() + case b.Field.Name.IsPeField(): + b.accessor = newPEAccessor() + case b.Field.Name.IsMemField(): + b.accessor = newMemAccessor() + case b.Field.Name.IsDNSField(): + b.accessor = newDNSAccessor() + } + return b.accessor +} 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 b79aa493d..60d2710fd 100644 --- a/pkg/filter/filter_test.go +++ b/pkg/filter/filter_windows_test.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2019-2020 by Nedim Sabic Sabic * https://www.fibratus.io @@ -60,7 +62,10 @@ var cfg = &config.Config{ EnableDNSEvents: 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 fdc0592ef..ee35c61da 100644 --- a/pkg/filter/ql/function.go +++ b/pkg/filter/ql/function.go @@ -21,17 +21,13 @@ 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/util/signature" - "golang.org/x/sys/windows" "github.com/rabbitstack/fibratus/pkg/filter/ql/functions" ) @@ -70,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{}, @@ -78,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{}, @@ -221,65 +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: - 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 + default: + return f.foreachPlatform(elems, segments, e, useCallValuer, valuer) } return false, false @@ -442,27 +390,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{} @@ -481,45 +408,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 } @@ -543,73 +436,3 @@ 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{} - 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_linux.go b/pkg/filter/ql/function_linux.go new file mode 100644 index 000000000..771982b79 --- /dev/null +++ b/pkg/filter/ql/function_linux.go @@ -0,0 +1,83 @@ +//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 ql + +import ( + "fmt" + + "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) { + 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_windows.go b/pkg/filter/ql/function_windows.go new file mode 100644 index 000000000..b8a527756 --- /dev/null +++ b/pkg/filter/ql/function_windows.go @@ -0,0 +1,231 @@ +//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 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. +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/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/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_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/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/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/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 f5562a40a..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) uint32 { - if !e.Callstack.IsEmpty() && e.Callstack.FrameAt(0).PID != 0 { - return 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/util_windows.go b/pkg/filter/util_windows.go new file mode 100644 index 000000000..69990d7db --- /dev/null +++ b/pkg/filter/util_windows.go @@ -0,0 +1,32 @@ +//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 filter + +import "github.com/rabbitstack/fibratus/pkg/event" + +// framePID returns the process identifier associated with the stack frame. +func framePID(e *event.Event) uint32 { + if !e.Callstack.IsEmpty() && e.Callstack.FrameAt(0).PID != 0 { + return e.Callstack.FrameAt(0).PID + } + return e.PID +} 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/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/outputs/config.go b/pkg/outputs/config.go index 41850daa6..117bc5c64 100644 --- a/pkg/outputs/config.go +++ b/pkg/outputs/config.go @@ -20,13 +20,40 @@ package outputs import ( "fmt" + + "github.com/rabbitstack/fibratus/pkg/util/mapdecoder" "github.com/spf13/pflag" ) +// ConfigLoader decodes raw config for a single output type when the output is enabled. +type ConfigLoader func(any) (Config, error) + +// ConfigLoaders is the registry of configured outputs. +type ConfigLoaders map[Type]ConfigLoader + // Config contains the output configuration. type Config struct { Type Type - Output interface{} + Output any +} + +// Register registers a new output config loader. +func (loaders ConfigLoaders) Register(typ Type, loader ConfigLoader) { + if _, ok := loaders[typ]; ok { + panic(fmt.Sprintf("output loader %q is already registered", typ)) + } + loaders[typ] = loader +} + +// LoadFromConfig builds an output loader for a config type T, decoding raw into it. +func LoadFromConfig[T any](typ Type) ConfigLoader { + return func(raw any) (Config, error) { + var cfg T + if err := mapdecoder.Decode(raw, &cfg); err != nil { + return Config{}, err + } + return Config{Type: typ, Output: cfg}, nil + } } // TLSConfig stores the client TLS parameters. 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/ps/snapshotter.go b/pkg/ps/snapshotter.go deleted file mode 100644 index f58f45403..000000000 --- a/pkg/ps/snapshotter.go +++ /dev/null @@ -1,69 +0,0 @@ -/* - * 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_linux.go b/pkg/ps/snapshotter_linux.go new file mode 100644 index 000000000..2f872399c --- /dev/null +++ b/pkg/ps/snapshotter_linux.go @@ -0,0 +1,167 @@ +//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 ps + +import ( + "sync" + + "github.com/rabbitstack/fibratus/pkg/event" + pstypes "github.com/rabbitstack/fibratus/pkg/ps/types" + "github.com/rabbitstack/fibratus/pkg/util/va" +) + +// 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 + // Find attempts to retrieve process state for the specified process identifier. + Find(pid uint32) (bool, *pstypes.PS) + // FindAndPut retrieves process state. Procfs fallback enrichment will be added + // when Linux capture is wired. + FindAndPut(pid uint32) *pstypes.PS + // Put inserts the process state into the snapshotter. + Put(*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 removes the thread from the given process. + RemoveThread(pid uint32, tid uint32) error + // AddMmap adds a memory mapping to the process state. + AddMmap(*event.Event) error + // RemoveMmap removes a memory mapping at the given base address. + RemoveMmap(pid uint32, addr va.Address) error +} + +type snapshotter struct { + mu sync.RWMutex + procs map[uint32]*pstypes.PS +} + +// NewSnapshotter builds an in-memory Linux process snapshotter. +func NewSnapshotter() Snapshotter { + return &snapshotter{procs: make(map[uint32]*pstypes.PS)} +} + +func (s *snapshotter) Find(pid uint32) (bool, *pstypes.PS) { + s.mu.RLock() + defer s.mu.RUnlock() + ps, ok := s.procs[pid] + return ok, ps +} + +func (s *snapshotter) FindAndPut(pid uint32) *pstypes.PS { + ok, ps := s.Find(pid) + if !ok { + return nil + } + return ps +} + +func (s *snapshotter) Put(ps *pstypes.PS) { + if ps == nil { + return + } + s.mu.Lock() + defer s.mu.Unlock() + s.procs[ps.PID] = ps +} + +func (s *snapshotter) Write(evt *event.Event) error { + if evt == nil || evt.PS == nil { + return nil + } + s.Put(evt.PS) + return nil +} + +func (s *snapshotter) 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 *snapshotter) Size() uint32 { + s.mu.RLock() + defer s.mu.RUnlock() + return uint32(len(s.procs)) +} + +func (s *snapshotter) Close() error { + s.mu.Lock() + defer s.mu.Unlock() + s.procs = make(map[uint32]*pstypes.PS) + return nil +} + +func (s *snapshotter) 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 *snapshotter) RemoveThread(pid uint32, tid uint32) error { + ok, ps := s.Find(pid) + if !ok || ps == nil { + return nil + } + ps.RemoveThread(tid) + return nil +} + +func (s *snapshotter) 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 *snapshotter) 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..06b10181f --- /dev/null +++ b/pkg/ps/snapshotter_linux_test.go @@ -0,0 +1,48 @@ +//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 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 TestSnapshotterFindPut(t *testing.T) { + s := NewSnapshotter() + 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/snapshotter_mock.go b/pkg/ps/snapshotter_mock_windows.go similarity index 99% rename from pkg/ps/snapshotter_mock.go rename to pkg/ps/snapshotter_mock_windows.go index 2b3dade65..b6f38c314 100644 --- a/pkg/ps/snapshotter_mock.go +++ b/pkg/ps/snapshotter_mock_windows.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2019-2020 by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/pkg/ps/snapshotter_windows.go b/pkg/ps/snapshotter_windows.go index b17179ad4..ac5cb65d2 100644 --- a/pkg/ps/snapshotter_windows.go +++ b/pkg/ps/snapshotter_windows.go @@ -57,6 +57,50 @@ var ( processEnrichments = expvar.NewInt("process.enrichments") ) +// 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 +} + type snapshotter struct { mu sync.RWMutex procs map[uint32]*pstypes.PS diff --git a/pkg/ps/types/types_linux.go b/pkg/ps/types/types_linux.go new file mode 100644 index 000000000..da1d56826 --- /dev/null +++ b/pkg/ps/types/types_linux.go @@ -0,0 +1,166 @@ +//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 types + +import ( + "encoding/binary" + "fmt" + "hash/fnv" + "sync" + "time" + + "github.com/rabbitstack/fibratus/pkg/util/va" +) + +// PS encapsulates Linux process state and its allocated resources. +type PS struct { + sync.RWMutex + // PID is the thread group identifier. It is also the thread identifier of the main thread. + PID uint32 `json:"pid"` + // Ppid is the thread group identifier of the parent process. + Ppid uint32 `json:"ppid"` + // Name is the process name. + Name string `json:"name"` + // Cmdline is the full process command line. + Cmdline string `json:"cmdline"` + // 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[uint32]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 [12]byte + binary.LittleEndian.PutUint32(key[:4], ps.PID) + binary.LittleEndian.PutUint64(key[4:], 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) { + ancestors = append(ancestors, fmt.Sprintf("%s (%d)", parent.Name, parent.PID)) + }, ps) + return ancestors +} + +// Thread stores identifiers for a Linux thread. +type Thread struct { + // Tid is the thread identifier. + Tid uint32 + // Pid is the thread group identifier to which the thread belongs. + Pid uint32 +} + +// Mmap stores information about a process memory mapping. +type Mmap struct { + // BaseAddress is the starting virtual address of the mapping. + BaseAddress va.Address + // 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[thread.Tid] = thread +} + +// RemoveThread removes a thread from the process state. +func (ps *PS) RemoveThread(tid uint32) { + 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 { + ps.Mmaps = append(ps.Mmaps[:i], ps.Mmaps[i+1:]...) + return + } + } +} + +// 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 { + return &ps.Mmaps[i] + } + } + return nil +} diff --git a/pkg/ps/types/types_linux_test.go b/pkg/ps/types/types_linux_test.go new file mode 100644 index 000000000..981c7478b --- /dev/null +++ b/pkg/ps/types/types_linux_test.go @@ -0,0 +1,35 @@ +//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 types + +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/rules/_fixtures/kill_action_linux.yml b/pkg/rules/_fixtures/kill_action_linux.yml new file mode 100644 index 000000000..46f117847 --- /dev/null +++ b/pkg/rules/_fixtures/kill_action_linux.yml @@ -0,0 +1,7 @@ +name: Kill process executed from a temporary directory +id: 33333333-3333-4333-8333-333333333333 +version: 1.0.0 +condition: evt.name = 'execve' and ps.exe imatches '/tmp/*' +action: + - name: kill +min-engine-version: 3.0.0 diff --git a/pkg/rules/_fixtures/shared/semantic_net.yml b/pkg/rules/_fixtures/shared/semantic_net.yml new file mode 100644 index 000000000..7039155b6 --- /dev/null +++ b/pkg/rules/_fixtures/shared/semantic_net.yml @@ -0,0 +1,5 @@ +name: match destination port +id: 22222222-2222-4222-8222-222222222222 +version: 1.0.0 +condition: evt.category = 'net' and net.dport = 443 +min-engine-version: 2.0.0 diff --git a/pkg/rules/_fixtures/shared/semantic_process.yml b/pkg/rules/_fixtures/shared/semantic_process.yml new file mode 100644 index 000000000..806e994e3 --- /dev/null +++ b/pkg/rules/_fixtures/shared/semantic_process.yml @@ -0,0 +1,5 @@ +name: match process category +id: 11111111-1111-4111-8111-111111111111 +version: 1.0.0 +condition: evt.category = 'process' +min-engine-version: 2.0.0 diff --git a/pkg/rules/action/isolate_linux.go b/pkg/rules/action/isolate_linux.go new file mode 100644 index 000000000..3684e56bb --- /dev/null +++ b/pkg/rules/action/isolate_linux.go @@ -0,0 +1,32 @@ +//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 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..59973e686 --- /dev/null +++ b/pkg/rules/action/kill_linux.go @@ -0,0 +1,204 @@ +//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 action + +import ( + "bytes" + "errors" + "fmt" + "os" + "slices" + "strconv" + + "github.com/rabbitstack/fibratus/pkg/config" + "github.com/rabbitstack/fibratus/pkg/event/params" + "github.com/rabbitstack/fibratus/pkg/util/multierror" + log "github.com/sirupsen/logrus" + "golang.org/x/sys/unix" +) + +// userHZ is the tick rate in which /proc//stat expresses the process start +// time. The kernel derives that field from task->start_boottime through +// nsec_to_clock_t, so dividing the captured nanoseconds by the same tick length +// reproduces it exactly. +const userHZ = uint64(100) + +const nsecPerTick = uint64(1_000_000_000) / userHZ + +type processInstance struct { + pid uint32 + startBootTime uint64 +} + +type killer struct { + open func(pid uint32) (int, error) + readStartTicks func(pid uint32) (uint64, error) + signal func(fd int, sig unix.Signal) error + closeFD func(fd int) error +} + +var defaultKiller = killer{ + open: openPidfd, + readStartTicks: readProcStartTicks, + signal: sendSignal, + closeFD: unix.Close, +} + +// Kill terminates each process referenced by the action context. +func Kill(ctx *config.ActionContext) error { + return defaultKiller.kill(ctx) +} + +func (k killer) kill(ctx *config.ActionContext) error { + if ctx == nil { + return nil + } + instances := processInstances(ctx) + log.Infof("killing pids=%v", pids(instances)) + + errs := make([]error, 0) + for _, inst := range instances { + if err := k.killInstance(inst); err != nil { + errs = append(errs, err) + } + } + return multierror.Wrap(errs...) +} + +// killInstance signals the process only if it is still the instance the rule +// matched on. The pidfd pins the process identifier for as long as it is open, +// so the identifier cannot be recycled between the start time comparison and +// the delivery of the signal. +func (k killer) killInstance(inst processInstance) error { + if inst.pid == 0 { + return fmt.Errorf("refusing to kill pid 0") + } + if inst.startBootTime == 0 { + return fmt.Errorf("refusing to kill pid %d: missing process start time", inst.pid) + } + + fd, err := k.open(inst.pid) + if err != nil { + if isGone(err) { + return nil + } + return fmt.Errorf("couldn't pin pid %d for termination: %v", inst.pid, err) + } + defer func() { + _ = k.closeFD(fd) + }() + + ticks, err := k.readStartTicks(inst.pid) + if err != nil { + if isGone(err) { + return nil + } + return fmt.Errorf("couldn't revalidate pid %d: %v", inst.pid, err) + } + if ticks != inst.startBootTime/nsecPerTick { + return fmt.Errorf("refusing to kill pid %d: process instance identity does not match captured start time", inst.pid) + } + + if err := k.signal(fd, unix.SIGKILL); err != nil { + if isGone(err) { + return nil + } + return fmt.Errorf("failed to kill pid %d: %v", inst.pid, err) + } + return nil +} + +// processInstances resolves the distinct process instances the rule matched on. +// Clone events already carry the child identity, so the event process +// identifier always designates the process the rule fired for. +func processInstances(ctx *config.ActionContext) []processInstance { + seen := make(map[uint32]processInstance, len(ctx.Events)) + for _, e := range ctx.Events { + if e == nil { + continue + } + start := e.GetParamAsUint64(params.StartBootTime) + if start == 0 && e.PS != nil { + start = e.PS.StartBootTime + } + seen[e.PID] = processInstance{pid: e.PID, startBootTime: start} + } + instances := make([]processInstance, 0, len(seen)) + for _, inst := range seen { + instances = append(instances, inst) + } + slices.SortFunc(instances, func(a, b processInstance) int { + return int(a.pid) - int(b.pid) + }) + return instances +} + +func pids(instances []processInstance) []uint32 { + p := make([]uint32, 0, len(instances)) + for _, inst := range instances { + p = append(p, inst.pid) + } + return p +} + +func openPidfd(pid uint32) (int, error) { + if pid > (^uint32(0) >> 1) { + return 0, fmt.Errorf("pid %d is out of range", pid) + } + return unix.PidfdOpen(int(pid), 0) +} + +func sendSignal(fd int, sig unix.Signal) error { + return unix.PidfdSendSignal(fd, sig, nil, 0) +} + +func readProcStartTicks(pid uint32) (uint64, error) { + data, err := os.ReadFile(fmt.Sprintf("/proc/%d/stat", pid)) + if err != nil { + return 0, err + } + return parseProcStatStartTicks(data) +} + +// parseProcStatStartTicks extracts the starttime field from a /proc//stat +// record. The comm field is parenthesized and may itself contain spaces and +// parentheses, so the field split starts after its final delimiter. +func parseProcStatStartTicks(stat []byte) (uint64, error) { + i := bytes.LastIndexByte(stat, ')') + if i < 0 { + return 0, fmt.Errorf("malformed /proc stat: missing comm") + } + fields := bytes.Fields(stat[i+1:]) + // starttime is the 22nd field, which is index 19 once pid and comm are cut + if len(fields) < 20 { + return 0, fmt.Errorf("malformed /proc stat: too few fields") + } + ticks, err := strconv.ParseUint(string(fields[19]), 10, 64) + if err != nil { + return 0, fmt.Errorf("malformed /proc stat starttime: %w", err) + } + return ticks, nil +} + +func isGone(err error) bool { + return errors.Is(err, os.ErrNotExist) || errors.Is(err, unix.ESRCH) +} diff --git a/pkg/rules/action/kill_linux_test.go b/pkg/rules/action/kill_linux_test.go new file mode 100644 index 000000000..41ba5e9dd --- /dev/null +++ b/pkg/rules/action/kill_linux_test.go @@ -0,0 +1,298 @@ +//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 action + +import ( + "fmt" + "os" + "os/exec" + "syscall" + "testing" + "time" + + "github.com/rabbitstack/fibratus/pkg/config" + "github.com/rabbitstack/fibratus/pkg/event" + "github.com/rabbitstack/fibratus/pkg/event/params" + pstypes "github.com/rabbitstack/fibratus/pkg/ps/types" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "golang.org/x/sys/unix" +) + +const ( + testPID = 4242 + testStartNs = uint64(1_234_500_000_000) + testStartTicks = testStartNs / nsecPerTick + testPidfd = 7 +) + +// recorder captures what a killer attempted so tests never signal a real process. +type recorder struct { + opened []uint32 + signaled []int + signals []unix.Signal + closed []int +} + +func (r *recorder) killer(ticks func(pid uint32) (uint64, error)) killer { + return killer{ + open: func(pid uint32) (int, error) { + r.opened = append(r.opened, pid) + return testPidfd, nil + }, + readStartTicks: ticks, + signal: func(fd int, sig unix.Signal) error { + r.signaled = append(r.signaled, fd) + r.signals = append(r.signals, sig) + return nil + }, + closeFD: func(fd int) error { + r.closed = append(r.closed, fd) + return nil + }, + } +} + +func constTicks(ticks uint64) func(uint32) (uint64, error) { + return func(uint32) (uint64, error) { return ticks, nil } +} + +func killEvent(pid uint32, startNs uint64) *event.Event { + return &event.Event{ + Type: event.Execve, + PID: pid, + PS: &pstypes.PS{ + PID: pid, + Name: "malware", + StartBootTime: startNs, + }, + Params: event.Params{ + params.ProcessID: {Name: params.ProcessID, Type: params.PID, Value: pid}, + params.StartBootTime: {Name: params.StartBootTime, Type: params.Uint64, Value: startNs}, + }, + } +} + +func killContext(evts ...*event.Event) *config.ActionContext { + return &config.ActionContext{Events: evts} +} + +func TestParseProcStatStartTicks(t *testing.T) { + stat := []byte("1 (systemd) S 0 1 1 0 -1 4194560 123 0 0 0 1 1 0 0 20 0 1 0 12345 123456 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n") + ticks, err := parseProcStatStartTicks(stat) + require.NoError(t, err) + assert.Equal(t, uint64(12345), ticks) + + // comm may contain spaces and parentheses + spaced := []byte("4242 (my (odd) process) S 1 4242 4242 0 -1 0 0 0 0 0 0 0 0 0 20 0 1 0 99 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n") + ticks, err = parseProcStatStartTicks(spaced) + require.NoError(t, err) + assert.Equal(t, uint64(99), ticks) + + _, err = parseProcStatStartTicks([]byte("1 systemd S 0 1")) + require.Error(t, err) + _, err = parseProcStatStartTicks([]byte("1 (systemd) S 0")) + require.Error(t, err) +} + +func TestReadProcStartTicks(t *testing.T) { + ticks, err := readProcStartTicks(uint32(os.Getpid())) + require.NoError(t, err) + assert.Greater(t, ticks, uint64(0)) + + _, err = readProcStartTicks(uint32(1 << 30)) + require.Error(t, err) + assert.True(t, isGone(err)) +} + +func TestKillSignalsMatchingInstance(t *testing.T) { + r := &recorder{} + k := r.killer(constTicks(testStartTicks)) + + require.NoError(t, k.kill(killContext(killEvent(testPID, testStartNs)))) + assert.Equal(t, []uint32{testPID}, r.opened) + assert.Equal(t, []int{testPidfd}, r.signaled) + assert.Equal(t, []unix.Signal{unix.SIGKILL}, r.signals) + assert.Equal(t, []int{testPidfd}, r.closed) +} + +func TestKillPinsProcessBeforeRevalidating(t *testing.T) { + r := &recorder{} + var openedBeforeRead bool + k := r.killer(func(uint32) (uint64, error) { + openedBeforeRead = len(r.opened) == 1 + return testStartTicks, nil + }) + + require.NoError(t, k.kill(killContext(killEvent(testPID, testStartNs)))) + assert.True(t, openedBeforeRead, "pidfd must be open before the start time is compared") +} + +func TestKillRefusesReusedPID(t *testing.T) { + r := &recorder{} + k := r.killer(constTicks(testStartTicks + 1)) + + err := k.kill(killContext(killEvent(testPID, testStartNs))) + require.Error(t, err) + assert.Contains(t, err.Error(), "process instance identity does not match") + assert.Empty(t, r.signaled) + assert.Equal(t, []int{testPidfd}, r.closed) +} + +func TestKillMissingProcessIsSuccess(t *testing.T) { + r := &recorder{} + k := r.killer(constTicks(testStartTicks)) + k.open = func(uint32) (int, error) { return 0, unix.ESRCH } + + require.NoError(t, k.kill(killContext(killEvent(testPID, testStartNs)))) + assert.Empty(t, r.signaled) +} + +func TestKillProcessExitingDuringRevalidationIsSuccess(t *testing.T) { + r := &recorder{} + k := r.killer(func(uint32) (uint64, error) { return 0, os.ErrNotExist }) + + require.NoError(t, k.kill(killContext(killEvent(testPID, testStartNs)))) + assert.Empty(t, r.signaled) + assert.Equal(t, []int{testPidfd}, r.closed) +} + +func TestKillESRCHOnSignalIsSuccess(t *testing.T) { + r := &recorder{} + k := r.killer(constTicks(testStartTicks)) + k.signal = func(int, unix.Signal) error { return unix.ESRCH } + + require.NoError(t, k.kill(killContext(killEvent(testPID, testStartNs)))) +} + +func TestKillRefusesMissingStartTime(t *testing.T) { + r := &recorder{} + k := r.killer(constTicks(testStartTicks)) + + evt := killEvent(testPID, 0) + evt.PS.StartBootTime = 0 + evt.Params.Remove(params.StartBootTime) + + err := k.kill(killContext(evt)) + require.Error(t, err) + assert.Contains(t, err.Error(), "missing process start time") + assert.Empty(t, r.opened) + assert.Empty(t, r.signaled) +} + +func TestKillUsesEventStartBootTimeWhenPSMissing(t *testing.T) { + r := &recorder{} + k := r.killer(constTicks(testStartTicks)) + + evt := killEvent(testPID, testStartNs) + evt.PS = nil + require.NoError(t, k.kill(killContext(evt))) + assert.Equal(t, []uint32{testPID}, r.opened) +} + +// Clone events carry the child identity, so the event pid designates the +// process the rule matched on without consulting the pid parameter. +func TestKillResolvesCloneChildPid(t *testing.T) { + r := &recorder{} + k := r.killer(constTicks(testStartTicks)) + + clone := killEvent(testPID, testStartNs) + clone.Type = event.Clone + clone.Params.Append(params.CloneFlags, params.Uint64, uint64(0)) + require.True(t, clone.IsCreateProcess()) + + require.NoError(t, k.kill(killContext(clone))) + assert.Equal(t, []uint32{testPID}, r.opened) +} + +func TestKillDeduplicatesAndOrdersPids(t *testing.T) { + r := &recorder{} + k := r.killer(constTicks(testStartTicks)) + + err := k.kill(killContext( + killEvent(90, testStartNs), + killEvent(12, testStartNs), + killEvent(90, testStartNs), + )) + require.NoError(t, err) + assert.Equal(t, []uint32{12, 90}, r.opened) +} + +func TestKillNilContext(t *testing.T) { + require.NoError(t, Kill(nil)) +} + +// TestKillTerminatesLiveProcess exercises the real pidfd and procfs path end to +// end, including the refusal branch when the captured start time disagrees. +func TestKillTerminatesLiveProcess(t *testing.T) { + start := func(t *testing.T) (uint32, *exec.Cmd, uint64) { + t.Helper() + cmd := exec.Command("sleep", "300") + require.NoError(t, cmd.Start()) + t.Cleanup(func() { + _ = cmd.Process.Kill() + _, _ = cmd.Process.Wait() + }) + pid := uint32(cmd.Process.Pid) + ticks, err := readProcStartTicks(pid) + require.NoError(t, err) + return pid, cmd, ticks * nsecPerTick + } + + t.Run("matching instance is terminated", func(t *testing.T) { + pid, cmd, startNs := start(t) + + require.NoError(t, Kill(killContext(killEvent(pid, startNs)))) + + state, err := cmd.Process.Wait() + require.NoError(t, err) + assert.Equal(t, syscall.SIGKILL, state.Sys().(syscall.WaitStatus).Signal()) + }) + + t.Run("mismatched instance is spared", func(t *testing.T) { + pid, _, startNs := start(t) + + err := Kill(killContext(killEvent(pid, startNs+uint64(time.Second)))) + require.Error(t, err) + assert.Contains(t, err.Error(), "process instance identity does not match") + + ticks, err := readProcStartTicks(pid) + require.NoError(t, err) + assert.Equal(t, startNs/nsecPerTick, ticks, "process should still be alive") + }) +} + +func TestOpenPidfdRejectsOutOfRangePid(t *testing.T) { + _, err := openPidfd(uint32(1) << 30) + require.Error(t, err) + assert.Contains(t, err.Error(), "out of range") +} + +func TestKillReportsUnexpectedOpenError(t *testing.T) { + r := &recorder{} + k := r.killer(constTicks(testStartTicks)) + k.open = func(uint32) (int, error) { return 0, fmt.Errorf("boom") } + + err := k.kill(killContext(killEvent(testPID, testStartNs))) + require.Error(t, err) + assert.Contains(t, err.Error(), "couldn't pin pid 4242") +} diff --git a/pkg/rules/action/kill_windows.go b/pkg/rules/action/kill_windows.go index 926414441..80da07678 100644 --- a/pkg/rules/action/kill_windows.go +++ b/pkg/rules/action/kill_windows.go @@ -20,14 +20,23 @@ package action import ( "fmt" - "github.com/rabbitstack/fibratus/pkg/util/multierror" - "golang.org/x/sys/windows" "os" "syscall" + + "github.com/rabbitstack/fibratus/pkg/config" + "github.com/rabbitstack/fibratus/pkg/util/multierror" + log "github.com/sirupsen/logrus" + "golang.org/x/sys/windows" ) -// Kill terminates all processes with specified pids. -func Kill(pids []uint32) error { +// Kill terminates all processes referenced by the action context. +func Kill(ctx *config.ActionContext) error { + if ctx == nil { + return nil + } + pids := ctx.UniquePids() + log.Infof("killing pids=%v", pids) + errs := make([]error, 0) for _, pid := range pids { err := terminate(pid) diff --git a/pkg/rules/compiler.go b/pkg/rules/compiler.go index a45a87bc4..f4fe6ae4b 100644 --- a/pkg/rules/compiler.go +++ b/pkg/rules/compiler.go @@ -21,8 +21,6 @@ package rules import ( "expvar" "fmt" - "slices" - "strings" semver "github.com/hashicorp/go-version" "github.com/rabbitstack/fibratus/pkg/config" @@ -61,6 +59,7 @@ type compiler struct { psnap ps.Snapshotter config *config.Config approvers config.Approvers + plan *filter.ApproverPlan } func newCompiler(psnap ps.Snapshotter, cfg *config.Config) *compiler { @@ -151,6 +150,7 @@ func (c *compiler) compile() (map[*config.FilterConfig]filter.Filter, *config.Ru } if len(filters) == 0 { + c.plan = filter.AllowAllPlan() return filters, nil, nil } @@ -159,9 +159,34 @@ func (c *compiler) compile() (map[*config.FilterConfig]filter.Filter, *config.Ru r.Approvers = c.approvers } + providers := make([]filter.Filter, 0, len(filters)) + for _, fltr := range filters { + if !isApproverScoped(fltr) { + continue + } + providers = append(providers, fltr) + } + c.plan = filter.BuildApproverPlan(providers) + return filters, r, nil } +func isApproverScoped(f filter.Filter) bool { + for name := range f.GetStringFields() { + if name == fields.EvtName || name == fields.EvtCategory { + return true + } + } + return false +} + +func (c *compiler) ApproverPlan() *filter.ApproverPlan { + if c == nil || c.plan == nil { + return filter.AllowAllPlan() + } + return c.plan +} + func (c *compiler) visitApproverPredicates(node ql.Node) { walk := func(n ql.Node) { expr, ok := n.(*ql.BinaryExpr) @@ -220,100 +245,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) { - expr, ok := n.(*ql.BinaryExpr) - if !ok { - return - } - lhs, ok := expr.LHS.(*ql.FieldLiteral) - if !ok || lhs.Field != fields.EvtName { - return - } - - vals, ok := rhsToStrings(expr.RHS) - if !ok { - return - } - - evts := make([]event.Type, 0, len(vals)) - for _, v := range vals { - typ, ok := event.ParseType(v) - if !ok { - continue - } - evts = append(evts, typ) - } - - for _, typ := range types { - if slices.Contains(evts, typ) { - contains = true - return - } - } - }) - return contains -} - -func (c *compiler) containsFieldMatch(root ql.Node, field fields.Field, op ql.Token, val string) bool { - var contains bool - ql.WalkFunc(root, func(n ql.Node) { - expr, ok := n.(*ql.BinaryExpr) - if !ok { - return - } - - lhs, ok := expr.LHS.(*ql.FieldLiteral) - if !ok || lhs.Field != field { - return - } - - if expr.Op != op { - return - } - - values, ok := rhsToStrings(expr.RHS) - if !ok { - return - } - for _, v := range values { - if strings.EqualFold(v, val) { - contains = true - return - } - } - }) - return contains -} - // isNegated walks up the AST to check if the given node // is a direct child of a NOT unary expression. func (c *compiler) isNegated(root ql.Node, node ql.Node) bool { @@ -367,13 +298,6 @@ func (c *compiler) buildCompileResult(filters map[*config.FilterConfig]filter.Fi if info.Subcategory == event.DNS { rs.HasDNSEvents = true } - if typ == event.MapViewOfSection || typ == event.UnmapViewOfSection { - rs.HasVAMapEvents = true - } - if typ == event.OpenProcess || typ == event.OpenThread || typ == event.SetThreadContext || - typ == event.CreateSymbolicLinkObject { - rs.HasAuditAPIEvents = true - } if m[typ] { continue @@ -381,6 +305,8 @@ func (c *compiler) buildCompileResult(filters map[*config.FilterConfig]filter.Fi events = append(events, typ) m[typ] = true + + updatePlatformCompileResult(rs, typ) } } } diff --git a/pkg/rules/compiler_linux.go b/pkg/rules/compiler_linux.go new file mode 100644 index 000000000..e6dbf4d9a --- /dev/null +++ b/pkg/rules/compiler_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 rules + +import ( + "github.com/rabbitstack/fibratus/pkg/config" + "github.com/rabbitstack/fibratus/pkg/event" + "github.com/rabbitstack/fibratus/pkg/filter/ql" +) + +func (*compiler) referencesApproverEvents(ql.Node) bool { + return false +} + +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..351280417 --- /dev/null +++ b/pkg/rules/compiler_linux_test.go @@ -0,0 +1,179 @@ +//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/event" + "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) +} + +func TestCompilerExtractableApproverPlan(t *testing.T) { + rule := filepath.Join(t.TempDir(), "openat.yml") + require.NoError(t, os.WriteFile(rule, []byte(`name: Temporary file open +id: 7c1c2d3e-4f5a-6789-abcd-ef0123456789 +version: 1.0.0 +min-engine-version: 3.0.0 +condition: evt.name = 'openat' and file.path startswith '/tmp' +`), 0o600)) + + cfg := &config.Config{ + EventSource: config.EventSourceConfig{EnableFileIOEvents: true}, + Filters: &config.Filters{ + Rules: config.Rules{FromPaths: []string{rule}}, + }, + } + c := newCompiler(ps.NewSnapshotter(), cfg) + _, result, err := c.compile() + require.NoError(t, err) + require.NotNil(t, result) + pol := c.ApproverPlan().Policy(event.Openat) + require.False(t, pol.DefaultAllow) + require.True(t, pol.RequireFilename) + require.Equal(t, []string{"/tmp"}, pol.FilePrefix) +} + +func TestCompilerShippedLinuxRules(t *testing.T) { + cfg := newLinuxConfig(filepath.Join("..", "..", "rules", "linux", "*.yml")) + c := newCompiler(ps.NewSnapshotter(), cfg) + filters, result, err := c.compile() + require.NoError(t, err) + require.NotEmpty(t, filters) + require.NotNil(t, result) + require.True(t, result.HasProcEvents) + require.True(t, result.HasNetworkEvents) + + // every shipped rule carries the labels the rule validator warns about + for f := range filters { + for _, label := range []string{"tactic.id", "tactic.name", "tactic.ref", "technique.id", "technique.name", "technique.ref"} { + require.True(t, f.HasLabel(label), "%s is missing the %s label", f.Name, label) + } + } + + plan := c.ApproverPlan() + require.True(t, plan.Policy(event.Execve).DefaultAllow) + require.True(t, plan.Policy(event.Connect).DefaultAllow) + require.True(t, plan.Policy(event.Ptrace).DefaultAllow) + require.True(t, plan.Policy(event.Kill).DefaultAllow) +} + +// The approver scopes a sequence rule to the event names and categories in its +// string fields, on the assumption that the engine indexes the sequence by that +// same set and so never evaluates a stage against any other type. Pin it here: +// if indexing ever widens, the approver would under-block and drop events a +// sequence stage needs. +func TestEngineIndexesSequenceByStringFieldTypes(t *testing.T) { + rule := filepath.Join(t.TempDir(), "sequence.yml") + require.NoError(t, os.WriteFile(rule, []byte(`name: Execve then unscoped stage +id: 8e2f1a5b-3c4d-4e6f-8a9b-0c1d2e3f4a5b +version: 1.0.0 +min-engine-version: 3.0.0 +condition: > + sequence + maxspan 1m + |evt.name = 'execve'| + |ps.pid = 5| +`), 0o600)) + + cfg := newLinuxConfig(rule) + e := NewEngine(ps.NewSnapshotter(), cfg) + _, err := e.Compile() + require.NoError(t, err) + + require.Len(t, e.filters.types[event.Execve], 1, "sequence must be indexed under execve") + for _, typ := range event.All() { + if typ == event.Execve { + continue + } + require.Empty(t, e.filters.types[typ], "sequence must not be indexed under %s", typ) + } + require.Empty(t, e.filters.categories, "sequence names no category") +} + +func TestCompilerSharedSemanticFixtures(t *testing.T) { + cfg := newLinuxConfig("_fixtures/shared/*.yml") + filters, result, err := newCompiler(ps.NewSnapshotter(), cfg).compile() + require.NoError(t, err) + require.Len(t, filters, 2) + require.NotNil(t, result) +} + +func TestCompilerRejectsWindowsEventNames(t *testing.T) { + rule := filepath.Join(t.TempDir(), "windows.yml") + require.NoError(t, os.WriteFile(rule, []byte(`name: Windows process execution +id: 5d17dc44-cc9f-4f13-9a31-23c6529ff46e +version: 1.0.0 +min-engine-version: 3.0.0 +condition: evt.name = 'CreateProcess' +`), 0o600)) + + cfg := &config.Config{ + Filters: &config.Filters{ + Rules: config.Rules{FromPaths: []string{rule}}, + }, + } + _, _, err := newCompiler(ps.NewSnapshotter(), cfg).compile() + require.EqualError(t, err, ErrUnknownEventName("Windows process execution", "CreateProcess").Error()) +} + +func TestCompilerRejectsDeprecatedFields(t *testing.T) { + rule := filepath.Join(t.TempDir(), "kevt.yml") + require.NoError(t, os.WriteFile(rule, []byte(`name: Deprecated field +id: 6d17dc44-cc9f-4f13-9a31-23c6529ff46e +version: 1.0.0 +min-engine-version: 3.0.0 +condition: kevt.name = 'execve' +`), 0o600)) + + cfg := &config.Config{ + Filters: &config.Filters{ + Rules: config.Rules{FromPaths: []string{rule}}, + }, + } + _, _, err := newCompiler(ps.NewSnapshotter(), cfg).compile() + require.Error(t, err) +} diff --git a/pkg/rules/compiler_windows.go b/pkg/rules/compiler_windows.go new file mode 100644 index 000000000..bf19b5f41 --- /dev/null +++ b/pkg/rules/compiler_windows.go @@ -0,0 +1,133 @@ +//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 ( + "slices" + "strings" + + "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.MapViewOfSection || typ == event.UnmapViewOfSection { + rs.HasVAMapEvents = true + } + if typ == event.OpenProcess || typ == event.OpenThread || typ == event.SetThreadContext || + typ == event.CreateSymbolicLinkObject { + rs.HasAuditAPIEvents = true + } +} + +func (c *compiler) containsEventTypes(root ql.Node, types ...event.Type) bool { + var contains bool + ql.WalkFunc(root, func(n ql.Node) { + expr, ok := n.(*ql.BinaryExpr) + if !ok { + return + } + lhs, ok := expr.LHS.(*ql.FieldLiteral) + if !ok || lhs.Field != fields.EvtName { + return + } + + vals, ok := rhsToStrings(expr.RHS) + if !ok { + return + } + + evts := make([]event.Type, 0, len(vals)) + for _, v := range vals { + typ, ok := event.ParseType(v) + if !ok { + continue + } + evts = append(evts, typ) + } + + for _, typ := range types { + if slices.Contains(evts, typ) { + contains = true + return + } + } + }) + return contains +} + +func (c *compiler) containsFieldMatch(root ql.Node, field fields.Field, op ql.Token, val string) bool { + var contains bool + ql.WalkFunc(root, func(n ql.Node) { + expr, ok := n.(*ql.BinaryExpr) + if !ok { + return + } + + lhs, ok := expr.LHS.(*ql.FieldLiteral) + if !ok || lhs.Field != field { + return + } + + if expr.Op != op { + return + } + + values, ok := rhsToStrings(expr.RHS) + if !ok { + return + } + for _, v := range values { + if strings.EqualFold(v, val) { + contains = true + return + } + } + }) + return contains +} diff --git a/pkg/rules/compiler_test.go b/pkg/rules/compiler_windows_test.go similarity index 99% rename from pkg/rules/compiler_test.go rename to pkg/rules/compiler_windows_test.go index 4bb2ab9bc..48463fe30 100644 --- a/pkg/rules/compiler_test.go +++ b/pkg/rules/compiler_windows_test.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2021-present by Nedim Sabic Sabic * https://www.fibratus.io @@ -82,6 +84,7 @@ func TestCompileEventCategoryFieldNames(t *testing.T) { {"_fixtures/field_values/incorrect_event_name_in_operator.yml", ErrUnknownEventName("match https connections", "CreateProc")}, {"_fixtures/field_values/correct_category_name_field.yml", nil}, {"_fixtures/field_values/incorrect_category_name_field.yml", ErrUnknownCategoryName("match https connections", "pipe")}, + {"_fixtures/shared/*.yml", nil}, } for _, tt := range tests { diff --git a/pkg/rules/engine.go b/pkg/rules/engine.go index 618880af8..b6ac00c0b 100644 --- a/pkg/rules/engine.go +++ b/pkg/rules/engine.go @@ -146,6 +146,16 @@ func NewEngine(psnap ps.Snapshotter, config *config.Config) *Engine { return e } +// ApproverPlan returns the conservative in-kernel prefilter derived from the +// compiled ruleset. RulesCompileResult stays a usage summary and is not used +// as predicate data. +func (e *Engine) ApproverPlan() *filter.ApproverPlan { + if e == nil || e.compiler == nil { + return filter.AllowAllPlan() + } + return e.compiler.ApproverPlan() +} + func (e *Engine) gcSequences() { for { <-e.scavenger.C @@ -303,8 +313,8 @@ func (e *Engine) processActions() error { for _, act := range actions { switch t := act.(type) { case config.KillAction: - log.Infof("executing kill action: pids=%v rule=%s", m.ctx.UniquePids(), f.Name) - if err := action.Kill(m.ctx.UniquePids()); err != nil { + log.Infof("executing kill action: rule=%s", f.Name) + if err := action.Kill(m.ctx); err != nil { return ErrRuleAction(f.Name, err) } case config.IsolateAction: diff --git a/pkg/rules/engine_linux_test.go b/pkg/rules/engine_linux_test.go new file mode 100644 index 000000000..d7ebb224f --- /dev/null +++ b/pkg/rules/engine_linux_test.go @@ -0,0 +1,286 @@ +//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 ( + "net" + "path/filepath" + "testing" + "time" + + "github.com/rabbitstack/fibratus/pkg/alertsender" + "github.com/rabbitstack/fibratus/pkg/config" + "github.com/rabbitstack/fibratus/pkg/event" + "github.com/rabbitstack/fibratus/pkg/event/params" + "github.com/rabbitstack/fibratus/pkg/ps" + pstypes "github.com/rabbitstack/fibratus/pkg/ps/types" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +type mockNoneSender struct{} + +func (s *mockNoneSender) Send(alertsender.Alert) error { return nil } +func (s *mockNoneSender) Type() alertsender.Type { return alertsender.None } +func (s *mockNoneSender) Shutdown() error { return nil } +func (s *mockNoneSender) SupportsMarkdown() bool { return true } + +func makeNoneSender(alertsender.Config) (alertsender.Sender, error) { + return &mockNoneSender{}, nil +} + +func init() { + alertsender.Register(alertsender.None, makeNoneSender) +} + +func newLinuxConfig(fromFiles ...string) *config.Config { + return &config.Config{ + EventSource: config.EventSourceConfig{ + EnableFileIOEvents: true, + EnableNetEvents: true, + EnableMemEvents: true, + }, + Filters: &config.Filters{ + Rules: config.Rules{ + FromPaths: fromFiles, + }, + Macros: config.Macros{ + FromPaths: []string{filepath.Join("..", "..", "rules", "linux", "macros", "*")}, + }, + }, + } +} + +func compileRules(t *testing.T, e *Engine) *config.RulesCompileResult { + t.Helper() + rs, err := e.Compile() + require.NoError(t, err) + require.NotNil(t, rs) + return rs +} + +func processEvent(t *testing.T, e *Engine, evt *event.Event) bool { + t.Helper() + match, err := e.ProcessEvent(evt) + require.NoError(t, err) + return match +} + +func testPS(name, exe string, pid uint64, start uint64) *pstypes.PS { + return &pstypes.PS{ + PID: pid, + Ppid: 1, + Name: name, + Cmdline: exe, + Exe: exe, + StartBootTime: start, + Parent: &pstypes.PS{PID: 1, Name: "systemd", StartBootTime: 1}, + } +} + +func TestNewEngineAcceptsSnapshotter(t *testing.T) { + cfg := &config.Config{Filters: &config.Filters{}} + e := NewEngine(ps.NewSnapshotter(), cfg) + require.NotNil(t, e) + require.NotNil(t, e.compiler) +} + +func TestCompileIndexesLinuxTypesAndCategories(t *testing.T) { + e := NewEngine(ps.NewSnapshotter(), newLinuxConfig( + filepath.Join("..", "..", "rules", "linux", "*.yml"), + "_fixtures/shared/*.yml", + )) + rs := compileRules(t, e) + + require.True(t, rs.HasProcEvents) + require.True(t, rs.HasNetworkEvents) + assert.Contains(t, rs.UsedEvents, event.Execve) + assert.Contains(t, rs.UsedEvents, event.Ptrace) + assert.Contains(t, rs.UsedEvents, event.Kill) + assert.Contains(t, rs.UsedEvents, event.Connect) + + assert.NotEmpty(t, e.filters.types[event.Execve]) + assert.NotEmpty(t, e.filters.types[event.Ptrace]) + assert.NotEmpty(t, e.filters.types[event.Kill]) + assert.NotEmpty(t, e.filters.types[event.Connect]) + assert.NotEmpty(t, e.filters.categories[event.Process.Index()]) + assert.NotEmpty(t, e.filters.categories[event.Net.Index()]) +} + +func TestRunLinuxDetectionRules(t *testing.T) { + require.NoError(t, alertsender.LoadAll([]alertsender.Config{{Type: alertsender.None}})) + + e := NewEngine(ps.NewSnapshotter(), newLinuxConfig(filepath.Join("..", "..", "rules", "linux", "*.yml"))) + compileRules(t, e) + + tmpPS := testPS("dropper", "/tmp/dropper", 4242, 200) + execTmp := &event.Event{ + Type: event.Execve, + Name: "execve", + Category: event.Process, + PID: 4242, + Timestamp: time.Now(), + PS: tmpPS, + Params: event.Params{ + params.ProcessID: {Name: params.ProcessID, Type: params.PID, Value: uint64(4242)}, + params.Exe: {Name: params.Exe, Type: params.Path, Value: "/tmp/dropper"}, + params.Retval: {Name: params.Retval, Type: params.Int64, Value: int64(0)}, + }, + Metadata: make(map[event.MetadataKey]any), + } + require.True(t, processEvent(t, e, execTmp)) + + ptrace := &event.Event{ + Type: event.Ptrace, + Name: "ptrace", + Category: event.Process, + PID: 4242, + Timestamp: time.Now(), + PS: testPS("injector", "/usr/bin/injector", 4242, 200), + Params: event.Params{ + params.ProcessID: {Name: params.ProcessID, Type: params.PID, Value: uint64(4242)}, + params.PtraceRequest: {Name: params.PtraceRequest, Type: params.Int64, Value: int64(16)}, + params.TargetProcessID: {Name: params.TargetProcessID, Type: params.Int64, Value: int64(99)}, + }, + Metadata: make(map[event.MetadataKey]any), + } + require.True(t, processEvent(t, e, ptrace)) + + sigkill := &event.Event{ + Type: event.Kill, + Name: "kill", + Category: event.Process, + PID: 4242, + Timestamp: time.Now(), + PS: testPS("killer", "/usr/bin/killer", 4242, 200), + Params: event.Params{ + params.ProcessID: {Name: params.ProcessID, Type: params.PID, Value: uint64(4242)}, + params.Signal: {Name: params.Signal, Type: params.Int32, Value: int32(9)}, + params.TargetProcessID: {Name: params.TargetProcessID, Type: params.Int64, Value: int64(99)}, + }, + Metadata: make(map[event.MetadataKey]any), + } + require.True(t, processEvent(t, e, sigkill)) + + selfKill := &event.Event{ + Type: event.Kill, + Name: "kill", + Category: event.Process, + PID: 4242, + Timestamp: time.Now(), + PS: testPS("killer", "/usr/bin/killer", 4242, 200), + Params: event.Params{ + params.ProcessID: {Name: params.ProcessID, Type: params.PID, Value: uint64(4242)}, + params.Signal: {Name: params.Signal, Type: params.Int32, Value: int32(9)}, + params.TargetProcessID: {Name: params.TargetProcessID, Type: params.Int64, Value: int64(4242)}, + }, + Metadata: make(map[event.MetadataKey]any), + } + require.False(t, processEvent(t, e, selfKill)) +} + +func TestLinuxLifecycleSequence(t *testing.T) { + require.NoError(t, alertsender.LoadAll([]alertsender.Config{{Type: alertsender.None}})) + + e := NewEngine(ps.NewSnapshotter(), newLinuxConfig(filepath.Join("..", "..", "rules", "linux", "command_and_control_interpreter_outbound_connection.yml"))) + compileRules(t, e) + + ps := testPS("bash", "/bin/bash", 4242, 200) + execve := &event.Event{ + Seq: 1, + Type: event.Execve, + Name: "execve", + Category: event.Process, + PID: 4242, + Timestamp: time.Now(), + PS: ps, + Params: event.Params{ + params.ProcessID: {Name: params.ProcessID, Type: params.PID, Value: uint64(4242)}, + params.Exe: {Name: params.Exe, Type: params.Path, Value: "/bin/bash"}, + params.Retval: {Name: params.Retval, Type: params.Int64, Value: int64(0)}, + }, + Metadata: make(map[event.MetadataKey]any), + } + connect := &event.Event{ + Seq: 2, + Type: event.Connect, + Name: "connect", + Category: event.Net, + PID: 4242, + Timestamp: time.Now().Add(time.Second), + PS: ps, + Params: event.Params{ + params.ProcessID: {Name: params.ProcessID, Type: params.PID, Value: uint64(4242)}, + params.SockFamily: {Name: params.SockFamily, Type: params.Uint16, Value: uint16(2)}, + params.NetDIP: {Name: params.NetDIP, Type: params.IPv4, Value: net.IPv4(1, 2, 3, 4).To4()}, + params.NetDport: {Name: params.NetDport, Type: params.Port, Value: uint16(4444)}, + }, + Metadata: make(map[event.MetadataKey]any), + } + + require.Len(t, e.sequences, 1) + ss := e.sequences[0] + require.True(t, ss.isInitialState()) + + require.False(t, processEvent(t, e, execve)) + require.False(t, ss.isInitialState(), "the execve stage should have advanced the machine") + + require.True(t, processEvent(t, e, connect)) + require.True(t, ss.isInitialState(), "a fired sequence resets for the next match") +} + +func TestSharedSemanticRuleFixtures(t *testing.T) { + require.NoError(t, alertsender.LoadAll([]alertsender.Config{{Type: alertsender.None}})) + + e := NewEngine(ps.NewSnapshotter(), newLinuxConfig("_fixtures/shared/*.yml")) + compileRules(t, e) + + proc := &event.Event{ + Type: event.Execve, + Name: "execve", + Category: event.Process, + PID: 7, + PS: testPS("bash", "/bin/bash", 7, 10), + Params: event.Params{}, + Metadata: make(map[event.MetadataKey]any), + } + netevt := &event.Event{ + Type: event.Connect, + Name: "connect", + Category: event.Net, + PID: 7, + PS: testPS("bash", "/bin/bash", 7, 10), + Params: event.Params{ + params.NetDport: {Name: params.NetDport, Type: params.Port, Value: uint16(443)}, + }, + Metadata: make(map[event.MetadataKey]any), + } + + require.True(t, processEvent(t, e, proc)) + require.True(t, processEvent(t, e, netevt)) +} + +func TestCompileKillActionRule(t *testing.T) { + e := NewEngine(ps.NewSnapshotter(), newLinuxConfig("_fixtures/kill_action_linux.yml")) + compileRules(t, e) + assert.NotEmpty(t, e.filters.types[event.Execve]) +} diff --git a/pkg/rules/engine_test.go b/pkg/rules/engine_windows_test.go similarity index 96% rename from pkg/rules/engine_test.go rename to pkg/rules/engine_windows_test.go index 96974545c..8e4b1a3ca 100644 --- a/pkg/rules/engine_test.go +++ b/pkg/rules/engine_windows_test.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2021-present by Nedim Sabic Sabic * https://www.fibratus.io @@ -174,6 +176,29 @@ func TestRunSimpleRules(t *testing.T) { } } +func TestSharedSemanticRuleFixtures(t *testing.T) { + e := NewEngine(new(ps.SnapshotterMock), newConfig("_fixtures/shared/*.yml")) + compileRules(t, e) + + proc := &event.Event{ + Type: event.CreateProcess, + PID: 859, + Params: event.Params{}, + Metadata: make(map[event.MetadataKey]any), + } + netevt := &event.Event{ + Type: event.Recv, + PID: 859, + Params: event.Params{ + params.NetDport: {Name: params.NetDport, Type: params.Uint16, Value: uint16(443)}, + }, + Metadata: make(map[event.MetadataKey]any), + } + + require.True(t, wrapProcessEvent(proc, e.ProcessEvent)) + require.True(t, wrapProcessEvent(netevt, e.ProcessEvent)) +} + func TestRunSequenceRule(t *testing.T) { log.SetLevel(log.DebugLevel) diff --git a/pkg/rules/sequence.go b/pkg/rules/sequence.go index dfc3d05f7..8564da761 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 := rhs.Params.MustGetPid() - if lhs.Type == event.CreateProcess && isFinalSlot { + if lhs.IsCreateProcess() && isFinalSlot { return 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 99% rename from pkg/rules/sequence_test.go rename to pkg/rules/sequence_windows_test.go index dcf475307..8c6b029ff 100644 --- a/pkg/rules/sequence_test.go +++ b/pkg/rules/sequence_windows_test.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2021-present by Nedim Sabic Sabic * https://www.fibratus.io diff --git a/pkg/symbolize/symbolizer_test.go b/pkg/symbolize/symbolizer_test.go index 506905880..2f0df0ea3 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) @@ -298,9 +299,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) 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_linux.go b/pkg/util/colorizer/colorizer_linux.go new file mode 100644 index 000000000..190af18c9 --- /dev/null +++ b/pkg/util/colorizer/colorizer_linux.go @@ -0,0 +1,23 @@ +//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 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..4341075e2 --- /dev/null +++ b/pkg/util/colorizer/colorizer_windows.go @@ -0,0 +1,45 @@ +//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 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 bedcaf323..95803e26d 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/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 "" +} diff --git a/pkg/util/log/logger_linux.go b/pkg/util/log/logger_linux.go new file mode 100644 index 000000000..7f90ed330 --- /dev/null +++ b/pkg/util/log/logger_linux.go @@ -0,0 +1,37 @@ +//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 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/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 e02e6989e..c9f32353d 100644 --- a/pkg/util/log/logger.go +++ b/pkg/util/log/logger_windows.go @@ -22,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/config/decoder.go b/pkg/util/mapdecoder/decoder.go similarity index 85% rename from pkg/config/decoder.go rename to pkg/util/mapdecoder/decoder.go index c63bad2cb..e5bfd9c1c 100644 --- a/pkg/config/decoder.go +++ b/pkg/util/mapdecoder/decoder.go @@ -1,5 +1,5 @@ /* - * Copyright 2019-2020 by Nedim Sabic Sabic + * Copyright 2019-2026 by Nedim Sabic Sabic * https://www.fibratus.io * All Rights Reserved. * @@ -16,15 +16,17 @@ * limitations under the License. */ -package config +package mapdecoder import ( - "github.com/mitchellh/mapstructure" "net" "reflect" + + "github.com/mitchellh/mapstructure" ) -func decode(input, output interface{}) error { +// Decode decodes the input type to output type. +func Decode(input, output any) error { var decoderConfig = &mapstructure.DecoderConfig{ Metadata: nil, Result: output, @@ -43,10 +45,10 @@ func decode(input, output interface{}) error { } func ipSliceDecodeHook() mapstructure.DecodeHookFunc { - return func(from reflect.Type, to reflect.Type, data interface{}) (interface{}, error) { + return func(from reflect.Type, to reflect.Type, data any) (any, error) { if to.Kind() == reflect.Slice && to.Elem() == reflect.TypeOf(net.IP(nil)) { switch v := data.(type) { - case []interface{}: + case []any: var ips []net.IP for _, s := range v { ip, ok := s.(string) diff --git a/pkg/util/ntstatus/status.go b/pkg/util/ntstatus/status.go index b7506c51e..6aaaa2b0c 100644 --- a/pkg/util/ntstatus/status.go +++ b/pkg/util/ntstatus/status.go @@ -1,3 +1,5 @@ +//go:build windows + /* * Copyright 2021-2022 by Nedim Sabic Sabic * https://www.fibratus.io 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..5a5140835 --- /dev/null +++ b/pkg/util/rest/rest_windows_test.go @@ -0,0 +1,53 @@ +//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" + "testing" + + "github.com/rabbitstack/fibratus/pkg/api" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestGetPipe(t *testing.T) { + listener, err := api.MakeListener(`npipe:///fibratus`) + 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)) +} diff --git a/pkg/util/signals/signals_linux.go b/pkg/util/signals/signals_linux.go new file mode 100644 index 000000000..f202280ba --- /dev/null +++ b/pkg/util/signals/signals_linux.go @@ -0,0 +1,47 @@ +//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 signals + +import ( + "os" + "os/signal" + "syscall" + + log "github.com/sirupsen/logrus" +) + +// Install setups the signal handler. Returns a blocking +// channel which receives an input after Interrupt or Term +// signals are triggered. +func Install() chan struct{} { + sigCh := make(chan os.Signal, 1) + signal.Notify(sigCh, os.Interrupt, syscall.SIGTERM) + + stopCh := make(chan struct{}) + + go func() { + sig := <-sigCh + log.Infof("got signal %q, shutting down...", sig) + stopCh <- struct{}{} + }() + + return stopCh +} diff --git a/pkg/util/signals/signals.go b/pkg/util/signals/signals_windows.go similarity index 98% rename from pkg/util/signals/signals.go rename to pkg/util/signals/signals_windows.go index d7670af07..d4d69a7f4 100644 --- a/pkg/util/signals/signals.go +++ b/pkg/util/signals/signals_windows.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/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 diff --git a/rules/linux/command_and_control_interpreter_outbound_connection.yml b/rules/linux/command_and_control_interpreter_outbound_connection.yml new file mode 100644 index 000000000..b6868d1e3 --- /dev/null +++ b/rules/linux/command_and_control_interpreter_outbound_connection.yml @@ -0,0 +1,32 @@ +name: Interpreter established an outbound connection +id: bf1a30dc-8e54-46c7-9b9c-28c3b7169129 +version: 1.0.0 +description: | + Identifies a script interpreter that executes and then opens an outbound + IP connection. This sequence is commonly used for reverse shells and + follow-on command and control after a dropper runs under bash, python, + or a similar interpreter. The socket families are AF_INET and AF_INET6, + so local UNIX domain sockets are out of scope. +labels: + tactic.id: TA0011 + tactic.name: Command and Control + tactic.ref: https://attack.mitre.org/tactics/TA0011/ + technique.id: T1071 + technique.name: Application Layer Protocol + technique.ref: https://attack.mitre.org/techniques/T1071/ +references: + - https://attack.mitre.org/techniques/T1071/ + +condition: > + sequence + maxspan 30s + by ps.uuid + |execve and ps.name in script_interpreters| + |connect and net.family in (2, 10) and net.dport != 0| + + +output: > + %1.ps.name connected to %2.net.dip:%2.net.dport after execution + +severity: high +min-engine-version: 3.0.0 diff --git a/rules/linux/defense_evasion_process_traced_via_ptrace.yml b/rules/linux/defense_evasion_process_traced_via_ptrace.yml new file mode 100644 index 000000000..3db43d734 --- /dev/null +++ b/rules/linux/defense_evasion_process_traced_via_ptrace.yml @@ -0,0 +1,27 @@ +name: Process traced via ptrace +id: 992bc26b-b4c2-47d8-bf76-e7fb895caa1e +version: 1.0.0 +description: | + Identifies a process attaching to another process with ptrace. + PTRACE_ATTACH and PTRACE_SEIZE are used to inspect or modify another + process, including for injection and credential theft. Requests denied + by the kernel also match, since a blocked attempt carries the same intent + and often precedes a privilege escalation attempt. +labels: + tactic.id: TA0005 + tactic.name: Defense Evasion + tactic.ref: https://attack.mitre.org/tactics/TA0005/ + technique.id: T1055 + technique.name: Process Injection + technique.ref: https://attack.mitre.org/techniques/T1055/ +references: + - https://man7.org/linux/man-pages/man2/ptrace.2.html + +condition: > + ptrace_attach and ps.target.pid != 0 and ps.target.pid != evt.pid + +output: > + %ps.name attached to process %ps.target.pid via ptrace + +severity: high +min-engine-version: 3.0.0 diff --git a/rules/linux/execution_process_executed_from_temporary_directory.yml b/rules/linux/execution_process_executed_from_temporary_directory.yml new file mode 100644 index 000000000..ecd5711f3 --- /dev/null +++ b/rules/linux/execution_process_executed_from_temporary_directory.yml @@ -0,0 +1,25 @@ +name: Process executed from a temporary directory +id: 640b10f4-e9ad-487d-a04a-917595ab93c4 +version: 1.0.0 +description: | + Identifies programs executed from world-writable temporary directories. + Adversaries stage payloads in /tmp, /var/tmp, or /dev/shm to avoid writing + into more tightly controlled filesystem locations. +labels: + tactic.id: TA0002 + tactic.name: Execution + tactic.ref: https://attack.mitre.org/tactics/TA0002/ + technique.id: T1059 + technique.name: Command and Scripting Interpreter + technique.ref: https://attack.mitre.org/techniques/T1059/ +references: + - https://attack.mitre.org/techniques/T1059/ + +condition: > + execve and ps.exe matches world_writable_exec_paths + +output: > + %ps.name executed %ps.exe from a world-writable directory + +severity: high +min-engine-version: 3.0.0 diff --git a/rules/linux/impact_process_terminated_via_sigkill.yml b/rules/linux/impact_process_terminated_via_sigkill.yml new file mode 100644 index 000000000..e2d5d5256 --- /dev/null +++ b/rules/linux/impact_process_terminated_via_sigkill.yml @@ -0,0 +1,32 @@ +name: Process terminated via SIGKILL +id: cada79b8-9cfe-4ee9-8240-d3550e0859a7 +version: 1.0.0 +description: | + Identifies a process sending SIGKILL to a different process. + Adversaries use SIGKILL to stop security agents, terminate forensic + tools, or disrupt services that cannot catch the signal. Requests denied + by the kernel also match, since a blocked attempt carries the same intent. + + The target keeps the pid_t sign of the syscall argument, so a negative + target denotes a process group and -1 denotes every process the caller is + permitted to signal. Narrow this rule with ps.target.pid < 0 to look only + for those broader terminations. Signals a process sends to its own group + are out of scope. +labels: + tactic.id: TA0040 + tactic.name: Impact + tactic.ref: https://attack.mitre.org/tactics/TA0040/ + technique.id: T1489 + technique.name: Service Stop + technique.ref: https://attack.mitre.org/techniques/T1489/ +references: + - https://man7.org/linux/man-pages/man2/kill.2.html + +condition: > + sigkill and ps.target.pid != 0 and ps.target.pid != evt.pid + +output: > + %ps.name sent SIGKILL to target %ps.target.pid + +severity: medium +min-engine-version: 3.0.0 diff --git a/rules/linux/macros/macros.yml b/rules/linux/macros/macros.yml new file mode 100644 index 000000000..9b87619fc --- /dev/null +++ b/rules/linux/macros/macros.yml @@ -0,0 +1,57 @@ +- macro: execve + expr: evt.name = 'execve' and evt.retval = 0 + description: | + Matches a successful program execution. Failed execve calls are excluded + because no new program image is mapped. + +- macro: ptrace + expr: evt.name = 'ptrace' + description: | + Matches a ptrace request, whether or not the kernel permitted it. + +- macro: ptrace_attach + expr: ptrace and (ps.ptrace.request = 16 or ps.ptrace.request = 16902) + description: | + Matches a PTRACE_ATTACH (16) or PTRACE_SEIZE (16902) request. Denied + attempts are in scope because they reveal the same intent. + +- macro: send_signal + expr: evt.name = 'kill' + description: | + Matches a kill syscall, whether or not the signal was delivered. + +- macro: sigkill + expr: send_signal and ps.signal = 9 + description: | + Matches a SIGKILL request. Denied attempts are in scope because they + reveal the same intent. + +- macro: connect + expr: evt.name = 'connect' + description: | + Matches a socket connect syscall. Refused and unreachable destinations + are in scope because they still indicate outbound intent. + +- macro: world_writable_exec_paths + list: + - '/tmp/*' + - '/var/tmp/*' + - '/dev/shm/*' + description: | + Common world-writable directories used to stage and execute payloads. + +- macro: script_interpreters + list: + - bash + - sh + - dash + - zsh + - python + - python3 + - perl + - php + - ruby + - node + - lua + description: | + Script interpreter process names commonly used for staging outbound access.