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 7e575f0
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 19 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: 0 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -195,8 +195,6 @@ golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v
golang.org/x/net v0.0.0-20210525063256-abc453219eb5/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.0.0-20210928044308-7d9f5e0b762b/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.0.0-20220127200216-cd36cc0744dd/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk=
golang.org/x/net v0.25.0 h1:d/OCCoBEUq33pjydKrGQhw7IlUPI2Oylr+8qLx49kac=
golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM=
golang.org/x/net v0.33.0 h1:74SYHlV8BIgHIFC/LrYkOGIwL19eTYXQ5wc6TBuO36I=
golang.org/x/net v0.33.0/go.mod h1:HXLR5J+9DxmrqMwG9qjGCxZ+zKXxBru04zlTvWlWuN4=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
Expand Down

0 comments on commit 7e575f0

Please sign in to comment.