Skip to content

Commit

Permalink
fix: check CAP_BPF by capget syscall
Browse files Browse the repository at this point in the history
It's more simple to check CAP_BPF by capget syscall than creating a bpf
prog, as creating bpf prog requires removing rlimit memlock.

Signed-off-by: Leon Hwang <hffilwlqm@gmail.com>
  • Loading branch information
Asphaltt committed Dec 28, 2024
1 parent b01cb60 commit 32f201c
Showing 1 changed file with 8 additions and 17 deletions.
25 changes: 8 additions & 17 deletions cli/cmd/env_detection.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,9 @@
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"
)
Expand Down Expand Up @@ -48,23 +45,17 @@ func detectKernel() error {
}
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",
})
hdr := unix.CapUserHeader{Version: unix.LINUX_CAPABILITY_VERSION_3}
var data [2]unix.CapUserData // why 2? pls check https://github.com/golang/go/issues/44312
err := unix.Capget(&hdr, &data[0])
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 or add the --privileged=true flag for Docker.")
}
return fmt.Errorf("failed to get the capabilities of the current process: %v", err)
}

return fmt.Errorf("failed to create bpf program: %v", err)
haveBpfCap := data[0].Permitted&unix.CAP_BPF != 0
if !haveBpfCap {
return fmt.Errorf("the current user does not have CAP_BPF to load bpf programs. Please run as root or use sudo or add the --privileged=true flag for Docker.")
}
defer prog.Close()

return nil
}
Expand Down

0 comments on commit 32f201c

Please sign in to comment.