-
-
Notifications
You must be signed in to change notification settings - Fork 327
/
config.go
94 lines (80 loc) · 2.19 KB
/
config.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
package wireguard
import (
"fmt"
"net"
"net/netip"
"time"
"golang.zx2c4.com/wireguard/wgctrl"
"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
)
func configureDevice(client *wgctrl.Client, settings Settings) (err error) {
deviceConfig, err := makeDeviceConfig(settings)
if err != nil {
return fmt.Errorf("making device configuration: %w", err)
}
err = client.ConfigureDevice(settings.InterfaceName, deviceConfig)
if err != nil {
return fmt.Errorf("configuring device: %w", err)
}
return nil
}
func makeDeviceConfig(settings Settings) (config wgtypes.Config, err error) {
privateKey, err := wgtypes.ParseKey(settings.PrivateKey)
if err != nil {
return config, ErrPrivateKeyInvalid
}
publicKey, err := wgtypes.ParseKey(settings.PublicKey)
if err != nil {
return config, fmt.Errorf("%w: %s", ErrPublicKeyInvalid, settings.PublicKey)
}
var preSharedKey *wgtypes.Key
if settings.PreSharedKey != "" {
preSharedKeyValue, err := wgtypes.ParseKey(settings.PreSharedKey)
if err != nil {
return config, ErrPreSharedKeyInvalid
}
preSharedKey = &preSharedKeyValue
}
var persistentKeepaliveInterval *time.Duration
if settings.PersistentKeepaliveInterval > 0 {
persistentKeepaliveInterval = new(time.Duration)
*persistentKeepaliveInterval = settings.PersistentKeepaliveInterval
}
firewallMark := settings.FirewallMark
config = wgtypes.Config{
PrivateKey: &privateKey,
ReplacePeers: true,
FirewallMark: &firewallMark,
Peers: []wgtypes.PeerConfig{
{
PublicKey: publicKey,
PresharedKey: preSharedKey,
AllowedIPs: []net.IPNet{
{
IP: net.IPv4(0, 0, 0, 0),
Mask: []byte{0, 0, 0, 0},
},
{
IP: net.IPv6zero,
Mask: []byte(net.IPv6zero),
},
},
PersistentKeepaliveInterval: persistentKeepaliveInterval,
ReplaceAllowedIPs: true,
Endpoint: &net.UDPAddr{
IP: settings.Endpoint.Addr().AsSlice(),
Port: int(settings.Endpoint.Port()),
},
},
},
}
return config, nil
}
func allIPv4() (prefix netip.Prefix) {
const bits = 0
return netip.PrefixFrom(netip.IPv4Unspecified(), bits)
}
func allIPv6() (prefix netip.Prefix) {
const bits = 0
return netip.PrefixFrom(netip.IPv6Unspecified(), bits)
}