-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
95 lines (81 loc) · 2.14 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package main
import (
"fmt"
"log"
"net"
"github.com/PraserX/ipconv"
"github.com/cilium/ebpf"
"github.com/vishvananda/netlink"
"golang.org/x/sys/unix"
)
//go:generate go run github.com/cilium/ebpf/cmd/bpf2go redirect ./ebpf/redirect.c -- -I./ebpf
func main() {
objs := &redirectObjects{}
if err := loadRedirectObjects(objs, nil); err != nil {
log.Fatalf("loading objects: %v", err)
}
defer objs.Close()
attachFilter("eth0", objs.redirectPrograms.Redirect)
ip := net.ParseIP("192.168.1.5")
nextHopIP := net.ParseIP("10.111.221.21")
enableRedirect(ip, nextHopIP, "eth1", objs.RedirectMapIpv4)
}
func attachFilter(attachTo string, program *ebpf.Program) error {
devID, err := net.InterfaceByName(attachTo)
if err != nil {
return fmt.Errorf("could not get interface ID: %w", err)
}
qdisc := &netlink.GenericQdisc{
QdiscAttrs: netlink.QdiscAttrs{
LinkIndex: devID.Index,
Handle: netlink.MakeHandle(0xffff, 0),
Parent: netlink.HANDLE_CLSACT,
},
QdiscType: "clsact",
}
err = netlink.QdiscReplace(qdisc)
if err != nil {
return fmt.Errorf("could not get replace qdisc: %w", err)
}
filter := &netlink.BpfFilter{
FilterAttrs: netlink.FilterAttrs{
LinkIndex: devID.Index,
Parent: netlink.HANDLE_MIN_EGRESS,
Handle: 1,
Protocol: unix.ETH_P_ALL,
},
Fd: program.FD(),
Name: program.String(),
DirectAction: true,
}
if err := netlink.FilterReplace(filter); err != nil {
return fmt.Errorf("failed to replace tc filter: %w", err)
}
return nil
}
func enableRedirect(src, nextHop net.IP, interfaceName string, ebpfMap *ebpf.Map) error {
eth1ID, err := net.InterfaceByName(interfaceName)
if err != nil {
return fmt.Errorf("could not get interface ID: %w", err)
}
key, err := ipconv.IPv4ToInt(src)
if err != nil {
return fmt.Errorf("convert ip failed %w", err)
}
next, err := ipconv.IPv4ToInt(nextHop)
if err != nil {
return fmt.Errorf("convert ip failed %w", err)
}
record := struct {
interfaceID uint32
nextHopIP uint32
}{
uint32(eth1ID.Index),
next,
}
err = ebpfMap.Put(key, record)
if err != nil {
return fmt.Errorf("add to map failed %w", err)
}
return nil
}