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 <[email protected]>
  • Loading branch information
Asphaltt committed Dec 28, 2024
1 parent b01cb60 commit 4bc96fc
Show file tree
Hide file tree
Showing 2 changed files with 10 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
2 changes: 2 additions & 0 deletions cli/cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,8 @@ func init() {
rootCmd.PersistentFlags().StringVarP(&globalConf.LoggerAddr, "logaddr", "l", "", "send logs to this server. -l /tmp/ecapture.log or -l tcp://127.0.0.1:8080")
rootCmd.PersistentFlags().StringVar(&globalConf.EventCollectorAddr, "eventaddr", "", "the server address that receives the captured event. --eventaddr tcp://127.0.0.1:8090, default: same as logaddr")
rootCmd.PersistentFlags().StringVar(&globalConf.Listen, "listen", eCaptureListenAddr, "listen on this address for http server, default: 127.0.0.1:28256")

rootCmd.SilenceUsage = true
}

// eventCollector
Expand Down

0 comments on commit 4bc96fc

Please sign in to comment.