From 8bd8274798bf94fbc11addb205272d412a16b108 Mon Sep 17 00:00:00 2001 From: Leon Hwang Date: Thu, 5 Dec 2024 20:15:20 +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 | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/cli/cmd/env_detection.go b/cli/cmd/env_detection.go index d9ec642a5..5a2e57628 100644 --- a/cli/cmd/env_detection.go +++ b/cli/cmd/env_detection.go @@ -15,10 +15,14 @@ package cmd import ( + "errors" "fmt" "runtime" + "github.com/cilium/ebpf" + "github.com/cilium/ebpf/asm" "github.com/gojue/ecapture/pkg/util/kernel" + "golang.org/x/sys/unix" ) func detectKernel() error { @@ -42,6 +46,28 @@ func detectKernel() error { return nil } +func detectBpfCap() error { + // BPF 权限检测 + 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 +76,9 @@ func detectEnv() error { return err } + if err := detectBpfCap(); err != nil { + return err + } + return nil }