2023-07-26 14:00:47 +02:00
|
|
|
//go:build linux && !android
|
|
|
|
|
2023-07-27 15:34:27 +02:00
|
|
|
package ebpf
|
2023-07-26 14:00:47 +02:00
|
|
|
|
|
|
|
import (
|
|
|
|
_ "embed"
|
|
|
|
"net"
|
|
|
|
|
|
|
|
"github.com/cilium/ebpf/link"
|
|
|
|
"github.com/cilium/ebpf/rlimit"
|
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
|
|
|
mapKeyProxyPort uint32 = 0
|
|
|
|
mapKeyWgPort uint32 = 1
|
|
|
|
)
|
|
|
|
|
2023-07-27 15:34:27 +02:00
|
|
|
//go:generate go run github.com/cilium/ebpf/cmd/bpf2go -cc clang-14 bpf src/portreplace.c --
|
2023-07-26 14:00:47 +02:00
|
|
|
|
2023-07-27 15:34:27 +02:00
|
|
|
// EBPF is a wrapper for eBPF program
|
|
|
|
type EBPF struct {
|
2023-07-26 14:00:47 +02:00
|
|
|
link link.Link
|
|
|
|
}
|
|
|
|
|
2023-07-27 15:34:27 +02:00
|
|
|
// NewEBPF create new EBPF instance
|
|
|
|
func NewEBPF() *EBPF {
|
|
|
|
return &EBPF{}
|
2023-07-26 14:00:47 +02:00
|
|
|
}
|
|
|
|
|
2023-07-27 15:34:27 +02:00
|
|
|
// Load load ebpf program
|
|
|
|
func (l *EBPF) Load(proxyPort, wgPort int) error {
|
2023-07-26 14:00:47 +02:00
|
|
|
// it required for Docker
|
|
|
|
err := rlimit.RemoveMemlock()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
ifce, err := net.InterfaceByName("lo")
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Load pre-compiled programs into the kernel.
|
|
|
|
objs := bpfObjects{}
|
|
|
|
err = loadBpfObjects(&objs, nil)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer func() {
|
|
|
|
_ = objs.Close()
|
|
|
|
}()
|
|
|
|
|
|
|
|
err = objs.XdpPortMap.Put(mapKeyProxyPort, uint16(proxyPort))
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
err = objs.XdpPortMap.Put(mapKeyWgPort, uint16(wgPort))
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
defer func() {
|
|
|
|
_ = objs.XdpPortMap.Close()
|
|
|
|
}()
|
|
|
|
|
|
|
|
l.link, err = link.AttachXDP(link.XDPOptions{
|
|
|
|
Program: objs.XdpProgFunc,
|
|
|
|
Interface: ifce.Index,
|
|
|
|
})
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2023-07-27 15:34:27 +02:00
|
|
|
// Free free ebpf program
|
|
|
|
func (l *EBPF) Free() error {
|
2023-07-26 14:00:47 +02:00
|
|
|
if l.link != nil {
|
|
|
|
return l.link.Close()
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|