-
Notifications
You must be signed in to change notification settings - Fork 109
Expand file tree
/
Copy pathclient_freebsd.go
More file actions
532 lines (430 loc) · 12.5 KB
/
Copy pathclient_freebsd.go
File metadata and controls
532 lines (430 loc) · 12.5 KB
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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
//go:build freebsd
// +build freebsd
package wgfreebsd
// #include <stdlib.h>
// #include <netinet/in.h>
import "C"
import (
"bytes"
"encoding/binary"
"fmt"
"net"
"os"
"runtime"
"time"
"unsafe"
"golang.org/x/sys/unix"
"golang.zx2c4.com/wireguard/wgctrl/internal/wgfreebsd/internal/nv"
"golang.zx2c4.com/wireguard/wgctrl/internal/wgfreebsd/internal/wgh"
"golang.zx2c4.com/wireguard/wgctrl/internal/wginternal"
"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
)
// ifGroupWG is the WireGuard interface group name passed to the kernel.
var ifGroupWG = [16]byte{0: 'w', 1: 'g'}
var _ wginternal.Client = &Client{}
// A Client provides access to FreeBSD WireGuard ioctl information.
type Client struct {
// Hooks which use system calls by default, but can also be swapped out
// during tests.
close func() error
ioctlIfgroupreq func(*wgh.Ifgroupreq) error
ioctlWGDataIO func(uint, *wgh.WGDataIO) error
}
// New creates a new Client and returns whether or not the ioctl interface
// is available.
func New() (*Client, bool, error) {
// The FreeBSD ioctl interface operates on a generic AF_INET socket.
fd, err := unix.Socket(unix.AF_INET, unix.SOCK_DGRAM, 0)
if err != nil {
return nil, false, err
}
// TODO(mdlayher): find a call to invoke here to probe for availability.
// c.Devices won't work because it returns a "not found" error when the
// kernel WireGuard implementation is available but the interface group
// has no members.
// By default, use system call implementations for all hook functions.
return &Client{
close: func() error { return unix.Close(fd) },
ioctlIfgroupreq: ioctlIfgroupreq(fd),
ioctlWGDataIO: ioctlWGDataIO(fd),
}, true, nil
}
// Close implements wginternal.Client.
func (c *Client) Close() error {
return c.close()
}
// Devices implements wginternal.Client.
func (c *Client) Devices() ([]*wgtypes.Device, error) {
ifg := wgh.Ifgroupreq{
// Query for devices in the "wg" group.
Name: ifGroupWG,
}
// Determine how many device names we must allocate memory for.
if err := c.ioctlIfgroupreq(&ifg); err != nil {
return nil, err
}
// ifg.Len is size in bytes; allocate enough memory for the correct number
// of wgh.Ifgreq and then store a pointer to the memory where the data
// should be written (ifgrs) in ifg.Groups.
//
// From a thread in golang-nuts, this pattern is valid:
// "It would be OK to pass a pointer to a struct to ioctl if the struct
// contains a pointer to other Go memory, but the struct field must have
// pointer type."
// See: https://groups.google.com/forum/#!topic/golang-nuts/FfasFTZvU_o.
ifgrs := make([]wgh.Ifgreq, ifg.Len/wgh.SizeofIfgreq)
ifg.Groups = &ifgrs[0]
// Now actually fetch the device names.
if err := c.ioctlIfgroupreq(&ifg); err != nil {
return nil, err
}
// Keep this alive until we're done doing the ioctl dance.
runtime.KeepAlive(&ifg)
devices := make([]*wgtypes.Device, 0, len(ifgrs))
for _, ifgr := range ifgrs {
// Remove any trailing NULL bytes from the interface names.
name := string(bytes.TrimRight(ifgr.Ifgrqu[:], "\x00"))
device, err := c.Device(name)
if err != nil {
return nil, err
}
devices = append(devices, device)
}
return devices, nil
}
// Device implements wginternal.Client.
func (c *Client) Device(name string) (*wgtypes.Device, error) {
dname, err := deviceName(name)
if err != nil {
return nil, err
}
// First, specify the name of the device and determine how much memory
// must be allocated.
data := wgh.WGDataIO{
Name: dname,
}
var mem []byte
for {
if err := c.ioctlWGDataIO(wgh.SIOCGWG, &data); err != nil {
// ioctl functions always return a wrapped unix.Errno value.
// Conform to the wgctrl contract by unwrapping some values:
// ENXIO: "no such device": (no such WireGuard device)
// EINVAL: "inappropriate ioctl for device" (device is not a
// WireGuard device)
switch err.(*os.SyscallError).Err {
case unix.ENXIO, unix.EINVAL:
return nil, os.ErrNotExist
default:
return nil, err
}
}
if len(mem) >= int(data.Size) {
// Allocated enough memory!
break
}
// Allocate the appropriate amount of memory and point the kernel at
// the first byte of our slice's backing array. When the loop continues,
// we will check if we've allocated enough memory.
mem = make([]byte, data.Size)
data.Data = &mem[0]
}
dev, err := parseDevice(mem)
if err != nil {
return nil, err
}
dev.Name = name
return dev, nil
}
// ConfigureDevice implements wginternal.Client.
func (c *Client) ConfigureDevice(name string, cfg wgtypes.Config) error {
// Check if there is a peer with the UpdateOnly flag set.
// This is not supported on FreeBSD yet. So error out..
// TODO(stv0g): remove this check once kernel support has landed.
for _, peer := range cfg.Peers {
if peer.UpdateOnly {
// Check that this device is really an existing kernel
// device
if _, err := c.Device(name); err != os.ErrNotExist {
return wgtypes.ErrUpdateOnlyNotSupported
}
}
}
m := unparseConfig(cfg)
mem, sz, err := nv.Marshal(m)
if err != nil {
return err
}
defer C.free(unsafe.Pointer(mem))
dname, err := deviceName(name)
if err != nil {
return err
}
data := wgh.WGDataIO{
Name: dname,
Data: mem,
Size: wgh.SizeT(sz),
}
if err := c.ioctlWGDataIO(wgh.SIOCSWG, &data); err != nil {
// ioctl functions always return a wrapped unix.Errno value.
// Conform to the wgctrl contract by unwrapping some values:
// ENXIO: "no such device": (no such WireGuard device)
// EINVAL: "inappropriate ioctl for device" (device is not a
// WireGuard device)
switch err.(*os.SyscallError).Err {
case unix.ENXIO, unix.EINVAL:
return os.ErrNotExist
default:
return err
}
}
return nil
}
// deviceName converts an interface name string to the format required to pass
// with wgh.WGGetServ.
func deviceName(name string) ([16]byte, error) {
var out [unix.IFNAMSIZ]byte
if len(name) > unix.IFNAMSIZ {
return out, fmt.Errorf("wgfreebsd: interface name %q too long", name)
}
copy(out[:], name)
return out, nil
}
// ioctlIfgroupreq returns a function which performs the appropriate ioctl on
// fd to retrieve members of an interface group.
func ioctlIfgroupreq(fd int) func(*wgh.Ifgroupreq) error {
return func(ifg *wgh.Ifgroupreq) error {
return ioctl(fd, unix.SIOCGIFGMEMB, unsafe.Pointer(ifg))
}
}
// ioctlWGDataIO returns a function which performs the appropriate ioctl on
// fd to issue a WireGuard data I/O.
func ioctlWGDataIO(fd int) func(uint, *wgh.WGDataIO) error {
return func(req uint, data *wgh.WGDataIO) error {
return ioctl(fd, req, unsafe.Pointer(data))
}
}
// ioctl is a raw wrapper for the ioctl system call.
func ioctl(fd int, req uint, arg unsafe.Pointer) error {
_, _, errno := unix.Syscall(unix.SYS_IOCTL, uintptr(fd), uintptr(req), uintptr(arg))
if errno != 0 {
return os.NewSyscallError("ioctl", errno)
}
return nil
}
func panicf(format string, a ...interface{}) {
panic(fmt.Sprintf(format, a...))
}
func ntohs(i uint16) int {
b := *(*[2]byte)(unsafe.Pointer(&i))
return int(binary.BigEndian.Uint16(b[:]))
}
func htons(i int) uint16 {
b := make([]byte, 2)
binary.BigEndian.PutUint16(b, uint16(i))
return *(*uint16)(unsafe.Pointer(&b[0]))
}
// parseEndpoint converts a struct sockaddr to a Go net.UDPAddr
func parseEndpoint(ep []byte) *net.UDPAddr {
sa := (*unix.RawSockaddr)(unsafe.Pointer(&ep[0]))
switch sa.Family {
case unix.AF_INET:
sa := (*unix.RawSockaddrInet4)(unsafe.Pointer(&ep[0]))
ep := &net.UDPAddr{
IP: make(net.IP, net.IPv4len),
Port: ntohs(sa.Port),
}
copy(ep.IP, sa.Addr[:])
return ep
case unix.AF_INET6:
sa := (*unix.RawSockaddrInet6)(unsafe.Pointer(&ep[0]))
// TODO(mdlayher): IPv6 zone?
ep := &net.UDPAddr{
IP: make(net.IP, net.IPv6len),
Port: ntohs(sa.Port),
}
copy(ep.IP, sa.Addr[:])
return ep
default:
// No endpoint configured.
return nil
}
}
func unparseEndpoint(ep net.UDPAddr) []byte {
var b []byte
if v4 := ep.IP.To4(); v4 != nil {
b = make([]byte, unsafe.Sizeof(unix.RawSockaddrInet4{}))
sa := (*unix.RawSockaddrInet4)(unsafe.Pointer(&b[0]))
sa.Family = unix.AF_INET
sa.Port = htons(ep.Port)
copy(sa.Addr[:], v4)
} else if v6 := ep.IP.To16(); v6 != nil {
b = make([]byte, unsafe.Sizeof(unix.RawSockaddrInet6{}))
sa := (*unix.RawSockaddrInet6)(unsafe.Pointer(&b[0]))
sa.Family = unix.AF_INET6
sa.Port = htons(ep.Port)
copy(sa.Addr[:], v6)
}
return b
}
// parseAllowedIP unpacks a net.IPNet from a WGAIP structure.
func parseAllowedIP(aip nv.List) net.IPNet {
cidr := int(aip["cidr"].(uint64))
if ip, ok := aip["ipv4"]; ok {
return net.IPNet{
IP: net.IP(ip.([]byte)),
Mask: net.CIDRMask(cidr, 32),
}
} else if ip, ok := aip["ipv6"]; ok {
return net.IPNet{
IP: net.IP(ip.([]byte)),
Mask: net.CIDRMask(cidr, 128),
}
} else {
panicf("wgfreebsd: invalid address family for allowed IP: %+v", aip)
return net.IPNet{}
}
}
func unparseAllowedIP(aip net.IPNet) nv.List {
m := nv.List{}
ones, _ := aip.Mask.Size()
m["cidr"] = uint64(ones)
if v4 := aip.IP.To4(); v4 != nil {
m["ipv4"] = []byte(v4)
} else if v6 := aip.IP.To16(); v6 != nil {
m["ipv6"] = []byte(v6)
}
return m
}
// parseTimestamp parses a binary timestamp to a Go time.Time
func parseTimestamp(b []byte) time.Time {
var secs, nsecs int64
buf := bytes.NewReader(b)
// TODO(stv0g): Handle non-little endian machines
binary.Read(buf, binary.LittleEndian, &secs)
binary.Read(buf, binary.LittleEndian, &nsecs)
if secs == 0 && nsecs == 0 {
return time.Time{}
}
return time.Unix(secs, nsecs)
}
// parsePeer unpacks a wgtypes.Peer from a name-value list (nvlist).
func parsePeer(v nv.List) wgtypes.Peer {
p := wgtypes.Peer{
ProtocolVersion: 1,
}
if v, ok := v["public-key"]; ok {
pk := (*wgtypes.Key)(v.([]byte))
p.PublicKey = *pk
}
if v, ok := v["preshared-key"]; ok {
psk := (*wgtypes.Key)(v.([]byte))
p.PresharedKey = *psk
}
if v, ok := v["last-handshake-time"]; ok {
p.LastHandshakeTime = parseTimestamp(v.([]byte))
}
if v, ok := v["endpoint"]; ok {
p.Endpoint = parseEndpoint(v.([]byte))
}
if v, ok := v["persistent-keepalive-interval"]; ok {
p.PersistentKeepaliveInterval = time.Second * time.Duration(v.(uint64))
}
if v, ok := v["rx-bytes"]; ok {
p.ReceiveBytes = int64(v.(uint64))
}
if v, ok := v["tx-bytes"]; ok {
p.TransmitBytes = int64(v.(uint64))
}
if v, ok := v["allowed-ips"]; ok {
m := v.([]nv.List)
for _, aip := range m {
p.AllowedIPs = append(p.AllowedIPs, parseAllowedIP(aip))
}
}
return p
}
// parseDevice decodes the device from a FreeBSD name-value list (nvlist)
func parseDevice(data []byte) (*wgtypes.Device, error) {
dev := &wgtypes.Device{
Type: wgtypes.FreeBSDKernel,
}
m := nv.List{}
if err := nv.Unmarshal(data, m); err != nil {
return nil, err
}
if v, ok := m["public-key"]; ok {
pk := (*wgtypes.Key)(v.([]byte))
dev.PublicKey = *pk
}
if v, ok := m["private-key"]; ok {
sk := (*wgtypes.Key)(v.([]byte))
dev.PrivateKey = *sk
}
if v, ok := m["user-cookie"]; ok {
dev.FirewallMark = int(v.(uint64))
}
if v, ok := m["listen-port"]; ok {
dev.ListenPort = int(v.(uint64))
}
if v, ok := m["peers"]; ok {
m := v.([]nv.List)
for _, n := range m {
peer := parsePeer(n)
dev.Peers = append(dev.Peers, peer)
}
}
return dev, nil
}
// unparsePeerConfig encodes a PeerConfig to a name-value list (nvlist).
func unparsePeerConfig(cfg wgtypes.PeerConfig) nv.List {
m := nv.List{}
m["public-key"] = cfg.PublicKey[:]
if v := cfg.PresharedKey; v != nil {
m["preshared-key"] = v[:]
}
if v := cfg.PersistentKeepaliveInterval; v != nil {
m["persistent-keepalive-interval"] = uint64(v.Seconds())
}
if v := cfg.Endpoint; v != nil {
m["endpoint"] = unparseEndpoint(*v)
}
if cfg.ReplaceAllowedIPs {
m["replace-allowedips"] = true
}
if cfg.Remove {
m["remove"] = true
}
if cfg.AllowedIPs != nil {
aips := []nv.List{}
for _, aip := range cfg.AllowedIPs {
aips = append(aips, unparseAllowedIP(aip))
}
m["allowed-ips"] = aips
}
return m
}
// unparseDevice encodes the device configuration as a FreeBSD name-value list (nvlist).
func unparseConfig(cfg wgtypes.Config) nv.List {
m := nv.List{}
if v := cfg.PrivateKey; v != nil {
m["private-key"] = v[:]
}
if v := cfg.ListenPort; v != nil {
m["listen-port"] = uint64(*v)
}
if v := cfg.FirewallMark; v != nil {
m["user-cookie"] = uint64(*v)
}
if cfg.ReplacePeers {
m["replace-peers"] = true
}
if v := cfg.Peers; v != nil {
peers := []nv.List{}
for _, p := range v {
peer := unparsePeerConfig(p)
peers = append(peers, peer)
}
m["peers"] = peers
}
return m
}