-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathwg.go
66 lines (59 loc) · 1.3 KB
/
wg.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
package main
import (
"encoding/base64"
"encoding/hex"
"fmt"
"net/netip"
"golang.zx2c4.com/wireguard/conn"
"golang.zx2c4.com/wireguard/device"
"golang.zx2c4.com/wireguard/tun"
"golang.zx2c4.com/wireguard/tun/netstack"
)
func base64ToHex(s string) string {
data, err := base64.StdEncoding.DecodeString(s)
if err != nil {
panic(err)
}
return hex.EncodeToString(data)
}
type Device struct {
tun.Device
dev *device.Device
*netstack.Net
}
func (d *Device) Close() error {
d.dev.Close()
return d.Device.Close()
}
func NewTun(conf *WgConf) (*Device, error) {
var localIPs []netip.Addr
var dnsIPs []netip.Addr
for _, ip := range conf.LocalIPs {
localIPs = append(localIPs, netip.MustParseAddr(ip))
}
for _, ip := range conf.DNSs {
dnsIPs = append(dnsIPs, netip.MustParseAddr(ip))
}
tunDev, n, err := netstack.CreateNetTUN(
localIPs,
dnsIPs,
conf.MTU)
if err != nil {
return nil, err
}
dev := device.NewDevice(tunDev, conn.NewDefaultBind(), device.NewLogger(device.LogLevelVerbose, ""))
err = dev.IpcSet(fmt.Sprintf(`private_key=%s
public_key=%s
endpoint=%s
allowed_ip=%s
`,
base64ToHex(conf.PrivateKey), base64ToHex(conf.PeerKey), conf.Endpoint, "0.0.0.0/0"))
if err != nil {
return nil, err
}
err = dev.Up()
if err != nil {
return nil, err
}
return &Device{tunDev, dev, n}, nil
}