-
Notifications
You must be signed in to change notification settings - Fork 43
/
wireguard.go
348 lines (282 loc) · 7.53 KB
/
wireguard.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
package wireguard
import (
"fmt"
"github.com/go-logr/logr"
"net"
"os/exec"
"syscall"
"github.com/jodevsa/wireguard-operator/pkg/agent"
"github.com/jodevsa/wireguard-operator/pkg/api/v1alpha1"
"github.com/vishvananda/netlink"
"golang.zx2c4.com/wireguard/wgctrl"
"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
)
const MTU = 1420
func syncRoute(_ agent.State, iface string) error {
link, err := netlink.LinkByName(iface)
if err != nil {
return err
}
routes, err := netlink.RouteList(link, syscall.AF_INET)
if err != nil {
return err
}
for _, route := range routes {
if route.LinkIndex == link.Attrs().Index {
return nil
}
}
route := netlink.Route{
LinkIndex: link.Attrs().Index,
Dst: &getIP("10.8.0.0/24")[0],
Gw: net.ParseIP("10.8.0.1"),
}
err = netlink.RouteAdd(&route)
if err != nil {
return err
}
return nil
}
func syncAddress(_ agent.State, iface string) error {
link, err := netlink.LinkByName(iface)
if err != nil {
return err
}
addresses, err := netlink.AddrList(link, syscall.AF_INET)
if err != nil {
return nil
}
if len(addresses) != 0 {
return nil
}
err = netlink.AddrAdd(link, &netlink.Addr{
IPNet: &net.IPNet{IP: net.ParseIP("10.8.0.1")},
})
if err := netlink.LinkSetUp(link); err != nil {
return err
}
return nil
}
func createLinkUsingUserspaceImpl(iface string, wgUserspaceImplementationFallback string) error {
bashCommand := fmt.Sprintf("mkdir -p /dev/net && if [ ! -c /dev/net/tun ]; then\n mknod /dev/net/tun c 10 200\nfi && %s %s", wgUserspaceImplementationFallback, iface)
cmd := exec.Command("bash", "-c", bashCommand)
err := cmd.Run()
if err != nil {
return err
}
return nil
}
func createLinkUsingKernalModule(iface string) error {
// link not created
wgLink := &netlink.GenericLink{
LinkAttrs: netlink.LinkAttrs{
Name: iface,
MTU: MTU,
},
LinkType: "wireguard",
}
if err := netlink.LinkAdd(wgLink); err != nil {
return err
}
return nil
}
func SyncLink(_ agent.State, iface string, wgUserspaceImplementationFallback string, wgUseUserspaceImpl bool) error {
link, err := netlink.LinkByName(iface)
if err != nil {
if _, ok := err.(netlink.LinkNotFoundError); !ok {
return err
}
}
if _, ok := err.(netlink.LinkNotFoundError); ok {
if wgUseUserspaceImpl {
err = createLinkUsingUserspaceImpl(iface, wgUserspaceImplementationFallback)
if err != nil {
return err
}
} else {
err = createLinkUsingKernalModule(iface)
if err != nil {
err = createLinkUsingUserspaceImpl(iface, wgUserspaceImplementationFallback)
if err != nil {
return err
}
}
}
link, err = netlink.LinkByName(iface)
if err != nil {
return err
}
if err := netlink.LinkSetUp(link); err != nil {
return err
}
}
link, err = netlink.LinkByName(iface)
if err != nil {
if _, ok := err.(netlink.LinkNotFoundError); !ok {
return err
}
}
addresses, err := netlink.AddrList(link, syscall.AF_INET)
if err != nil {
return nil
}
if len(addresses) != 0 {
return nil
}
err = netlink.AddrAdd(link, &netlink.Addr{
IPNet: &getIP("10.8.0.1/32")[0],
})
if err := netlink.LinkSetUp(link); err != nil {
return err
}
return nil
}
func (wg *Wireguard) syncWireguard(state agent.State, iface string, listenPort int) error {
c, _ := wgctrl.New()
cfg, err := CreateWireguardConfiguration(state, iface, listenPort)
if err != nil {
return err
}
err = c.ConfigureDevice(iface, cfg)
if err != nil {
return err
}
for _, peer := range cfg.Peers {
if peer.Remove {
wg.Logger.V(2).Info("Removed peer", "peerIP", peer.AllowedIPs[0].String(), "peerPublicKey", peer.PublicKey.String())
} else if peer.UpdateOnly {
wg.Logger.V(2).Info("Updated peer", "peerIP", peer.AllowedIPs[0].String(), "peerPublicKey", peer.PublicKey.String())
} else {
wg.Logger.V(2).Info("Added peer", "peerIP", peer.AllowedIPs[0].String(), "peerPublicKey", peer.PublicKey.String())
}
}
return nil
}
type Wireguard struct {
Logger logr.Logger
Iface string
ListenPort int
WgUserspaceImplementationFallback string
WgUseUserspaceImpl bool
}
func (wg *Wireguard) Sync(state agent.State) error {
wg.Logger.Info("syncing Wireguard")
// create wg0 link
err := SyncLink(state, wg.Iface, wg.WgUserspaceImplementationFallback, wg.WgUseUserspaceImpl)
if err != nil {
return err
}
// route all traffic coming from 10.8.0.0/24 via gateway 10.8.0.1 on wg0
err = syncRoute(state, wg.Iface)
if err != nil {
return err
}
// set wg0 gateway as 10.8.0.1/32
err = syncAddress(state, wg.Iface)
if err != nil {
return err
}
// sync wg configuration
err = wg.syncWireguard(state, wg.Iface, wg.ListenPort)
if err != nil {
return err
}
return nil
}
func getIP(ip string) []net.IPNet {
_, ipnet, _ := net.ParseCIDR(ip)
return []net.IPNet{*ipnet}
}
func createPeersConfiguration(state agent.State, iface string) ([]wgtypes.PeerConfig, error) {
var peersState = make(map[string]v1alpha1.WireguardPeer)
for _, peer := range state.Peers {
peersState[peer.Spec.PublicKey] = peer
}
c, err := wgctrl.New()
if err != nil {
return []wgtypes.PeerConfig{}, err
}
device, err := c.Device(iface)
if err != nil {
return []wgtypes.PeerConfig{}, err
}
var peerConfigurationByPublicKey = make(map[string]wgtypes.PeerConfig)
var existingConfgiuredPeersByPublicKey = make(map[string]bool)
for _, peer := range device.Peers {
existingConfgiuredPeersByPublicKey[peer.PublicKey.String()] = true
peerState, ok := peersState[peer.PublicKey.String()]
if !ok {
// delete peer
p := wgtypes.PeerConfig{
Remove: true,
AllowedIPs: peer.AllowedIPs,
PublicKey: peer.PublicKey,
}
peerConfigurationByPublicKey[p.PublicKey.String()] = p
} else {
if peerState.Spec.Disabled || peerState.Spec.PublicKey == "" {
// delete peer
p := wgtypes.PeerConfig{
Remove: true,
AllowedIPs: peer.AllowedIPs,
PublicKey: peer.PublicKey,
}
peerConfigurationByPublicKey[p.PublicKey.String()] = p
} else if peer.AllowedIPs[0].IP.String() != peerState.Spec.Address {
// update peer
p := wgtypes.PeerConfig{
UpdateOnly: true,
AllowedIPs: getIP(peerState.Spec.Address + "/32"),
PublicKey: peer.PublicKey,
ReplaceAllowedIPs: true,
}
peerConfigurationByPublicKey[p.PublicKey.String()] = p
}
}
}
// add new peers
for _, peer := range state.Peers {
if peer.Spec.Disabled == true {
continue
}
if peer.Spec.PublicKey == "" {
continue
}
if peer.Spec.Address == "" {
continue
}
key, err := wgtypes.ParseKey(peer.Spec.PublicKey)
if err != nil {
return []wgtypes.PeerConfig{}, err
}
_, ok := existingConfgiuredPeersByPublicKey[key.String()]
if ok {
continue
}
// create peer
p := wgtypes.PeerConfig{
AllowedIPs: getIP(peer.Spec.Address + "/32"),
PublicKey: key,
}
peerConfigurationByPublicKey[p.PublicKey.String()] = p
}
l := make([]wgtypes.PeerConfig, 0, len(peerConfigurationByPublicKey))
for _, value := range peerConfigurationByPublicKey {
l = append(l, value)
}
return l, nil
}
func CreateWireguardConfiguration(state agent.State, iface string, listenPort int) (wgtypes.Config, error) {
cfg := wgtypes.Config{}
key, err := wgtypes.ParseKey(state.ServerPrivateKey)
if err != nil {
return wgtypes.Config{}, err
}
cfg.PrivateKey = &key
// make sure we do not interrupt existing sessions
cfg.ReplacePeers = false
cfg.ListenPort = &listenPort
peers, err := createPeersConfiguration(state, iface)
cfg.Peers = peers
return cfg, nil
}