57 lines
1.4 KiB
Go
57 lines
1.4 KiB
Go
|
package gowgpkg
|
||
|
|
||
|
import (
|
||
|
"fmt"
|
||
|
"net"
|
||
|
"golang.zx2c4.com/wireguard/wgctrl"
|
||
|
"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
|
||
|
)
|
||
|
|
||
|
func PeerAdd(deviceName string, PeerPublicKey string, PeerPresharedKey string, ipList []net.IPNet, endpoint *net.UDPAddr) (error) {
|
||
|
client, err := wgctrl.New()
|
||
|
if err != nil {
|
||
|
return fmt.Errorf("Cant create wgctrl: %w", err)
|
||
|
}
|
||
|
|
||
|
pubKey, err := wgtypes.ParseKey(PeerPublicKey)
|
||
|
if err != nil {
|
||
|
return fmt.Errorf("Cant parse public key: %e", err)
|
||
|
}
|
||
|
|
||
|
var preKey *wgtypes.Key
|
||
|
if PeerPresharedKey != "" {
|
||
|
presharedKey, err := wgtypes.ParseKey(PeerPresharedKey)
|
||
|
if err != nil {
|
||
|
return fmt.Errorf("Cant parse preshared key: %e", err)
|
||
|
}
|
||
|
preKey = &presharedKey
|
||
|
}
|
||
|
|
||
|
peerConfig := wgtypes.PeerConfig{
|
||
|
PublicKey: pubKey,
|
||
|
Remove: false,
|
||
|
UpdateOnly: false,
|
||
|
PresharedKey: preKey,
|
||
|
Endpoint: endpoint,
|
||
|
PersistentKeepaliveInterval: nil,
|
||
|
ReplaceAllowedIPs: true,
|
||
|
AllowedIPs: ipList,
|
||
|
}
|
||
|
var peerConfigs []wgtypes.PeerConfig
|
||
|
peerConfigs = append(peerConfigs, peerConfig)
|
||
|
|
||
|
config := wgtypes.Config{
|
||
|
PrivateKey: nil,
|
||
|
ListenPort: nil,
|
||
|
FirewallMark: nil,
|
||
|
ReplacePeers: false,
|
||
|
Peers: peerConfigs,
|
||
|
}
|
||
|
|
||
|
err = client.ConfigureDevice(deviceName, config)
|
||
|
if err != nil {
|
||
|
return fmt.Errorf("Cant add peer: %e", err)
|
||
|
}
|
||
|
|
||
|
return nil
|
||
|
}
|