From 02682b1619ef87157945d7fd39969c07e610d1ad Mon Sep 17 00:00:00 2001 From: Leon Hwang Date: Thu, 5 Dec 2024 13:16:31 +0800 Subject: [PATCH] feat: Detect CAP_BPF when detect env If no capability to run bpf progs, we must check CAP_BPF asap. Without this check, there will be many noisy logs before log "error:operation not permitted", like https://github.com/gojue/ecapture/issues/678#issuecomment-2514532902. Signed-off-by: Leon Hwang --- cli/cmd/env_detection.go | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/cli/cmd/env_detection.go b/cli/cmd/env_detection.go index d9ec642a5..013323b1c 100644 --- a/cli/cmd/env_detection.go +++ b/cli/cmd/env_detection.go @@ -15,9 +15,14 @@ package cmd import ( + "errors" "fmt" "runtime" + "github.com/cilium/ebpf" + "github.com/cilium/ebpf/asm" + "golang.org/x/sys/unix" + "github.com/gojue/ecapture/pkg/util/kernel" ) @@ -43,6 +48,28 @@ func detectKernel() error { return nil } +func detectBpfCap() error { + prog, err := ebpf.NewProgram(&ebpf.ProgramSpec{ + Name: "uprobe_dummy", + Type: ebpf.Kprobe, + Instructions: asm.Instructions{ + asm.Mov.Imm(asm.R0, 0), + asm.Return(), + }, + License: "GPL", + }) + if err != nil { + if errors.Is(err, unix.EPERM) { + return fmt.Errorf("the current user does not have CAP_BPF to load bpf programs. Please run as root or use sudo.") + } + + return fmt.Errorf("failed to create bpf program: %v", err) + } + defer prog.Close() + + return nil +} + func detectEnv() error { // 环境检测 @@ -50,5 +77,9 @@ func detectEnv() error { return err } + if err := detectBpfCap(); err != nil { + return err + } + return nil }