netbird/iface/iface.go

292 lines
6.7 KiB
Go
Raw Normal View History

2021-05-01 12:45:37 +02:00
package iface
2021-06-24 11:46:33 +02:00
import (
"fmt"
2021-06-24 11:46:33 +02:00
"net"
"sync"
"time"
log "github.com/sirupsen/logrus"
"golang.zx2c4.com/wireguard/wgctrl"
"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
2021-06-24 11:46:33 +02:00
)
const (
DefaultMTU = 1280
DefaultWgPort = 51820
2021-06-24 11:46:33 +02:00
)
Refactor Interface package and update windows driver (#192) * script to generate syso files * test wireguard-windows driver package * set int log * add windows test * add windows test * verbose bash * use cd * move checkout * exit 0 * removed tty flag * artifact path * fix tags and add cache * fix cache * fix cache * test dir * restore artifacts in the root * try dll file * try dll file * copy dll * typo in copy dll * compile test * checkout first * updated cicd * fix add address issue and gen GUID * psexec typo * accept eula * mod tidy before tests * regular test exec and verbose test with psexec * test all * return WGInterface Interface * use WgIfaceName and timeout after 30 seconds * different ports and validate connect 2 peers * Use time.After for timeout and close interface * Use time.After for testing connect peers * WG Interface struct * Update engine and parse address * refactor Linux create and assignAddress * NewWGIface and configuration methods * Update proxy with interface methods * update up command test * resolve lint warnings * remove psexec test * close copied files * add goos before build * run tests on mac,windows and linux * cache by testing os * run on push * fix indentation * adjust test timeouts * remove parallel flag * mod tidy before test * ignore syso files * removed functions and renamed vars * different IPs for connect peers test * Generate syso with DLL * Single Close method * use port from test constant * test: remove wireguard interfaces after finishing engine test * use load_wgnt_from_rsrc Co-authored-by: braginini <bangvalo@gmail.com>
2022-01-17 14:01:58 +01:00
// NetInterface represents a generic network tunnel interface
type NetInterface interface {
Close() error
2021-06-24 11:46:33 +02:00
}
// WGIface represents a interface instance
type WGIface struct {
name string
address WGAddress
mtu int
netInterface NetInterface
mu sync.Mutex
}
// NewWGIFace Creates a new Wireguard interface instance
func NewWGIFace(iface string, address string, mtu int) (*WGIface, error) {
wgIface := &WGIface{
name: iface,
mtu: mtu,
mu: sync.Mutex{},
2021-06-24 11:46:33 +02:00
}
feature: Support live peer list update (#51) * created InitializePeer and ClosePeerConnection functions * feature: simplify peer stopping * chore: remove unused code * feature: basic management service implementation (#44) * feat: basic management service implementation [FAILING TESTS] * test: fix healthcheck test * test: #39 add peer registration endpoint test * feat: #39 add setup key handling * feat: #39 add peer management store persistence * refactor: extract config read/write to the utility package * refactor: move file contents copy to the utility package * refactor: use Accounts instead of Users in the Store * feature: add management server Docker file * refactor: introduce datadir instead of config * chore: use filepath.Join to concat filepaths instead of string concat * refactor: move stop channel to the root * refactor: move stop channel to the root * review: fix PR review notes Co-authored-by: braginini <hello@wiretrustee.com> * Handle read config file errors * feature: add letsencrypt support to the management service * fix: lint warnings * chore: change default datadir * refactor: set default flags in code not Dockerfile * chore: remove unused code * Added RemovePeer and centralized configureDevice code * remove peer from the wg interface when closing proxy * remove config file * add iface tests * fix tests, validate if file exists before removing it * removed unused functions UpdateListenPort and ConfigureWithKeyGen * Ensure we don't wait for timeout when closing * Rename ClosePeerConnection to RemovePeerConnection * Avoid returning on uapi Accept failures * Added engine tests * Remove extra add address code * Adding iface.Close * Ensure Close the interface and disable parallel test execution * check err var when listing interfaces * chore: add synchronisation to peer management * chore: add connection status to track peer connection * refactor: remove unused code Co-authored-by: braginini <hello@wiretrustee.com> Co-authored-by: Mikhail Bragin <bangvalo@gmail.com>
2021-07-19 15:02:11 +02:00
wgAddress, err := parseWGAddress(address)
feature: Support live peer list update (#51) * created InitializePeer and ClosePeerConnection functions * feature: simplify peer stopping * chore: remove unused code * feature: basic management service implementation (#44) * feat: basic management service implementation [FAILING TESTS] * test: fix healthcheck test * test: #39 add peer registration endpoint test * feat: #39 add setup key handling * feat: #39 add peer management store persistence * refactor: extract config read/write to the utility package * refactor: move file contents copy to the utility package * refactor: use Accounts instead of Users in the Store * feature: add management server Docker file * refactor: introduce datadir instead of config * chore: use filepath.Join to concat filepaths instead of string concat * refactor: move stop channel to the root * refactor: move stop channel to the root * review: fix PR review notes Co-authored-by: braginini <hello@wiretrustee.com> * Handle read config file errors * feature: add letsencrypt support to the management service * fix: lint warnings * chore: change default datadir * refactor: set default flags in code not Dockerfile * chore: remove unused code * Added RemovePeer and centralized configureDevice code * remove peer from the wg interface when closing proxy * remove config file * add iface tests * fix tests, validate if file exists before removing it * removed unused functions UpdateListenPort and ConfigureWithKeyGen * Ensure we don't wait for timeout when closing * Rename ClosePeerConnection to RemovePeerConnection * Avoid returning on uapi Accept failures * Added engine tests * Remove extra add address code * Adding iface.Close * Ensure Close the interface and disable parallel test execution * check err var when listing interfaces * chore: add synchronisation to peer management * chore: add connection status to track peer connection * refactor: remove unused code Co-authored-by: braginini <hello@wiretrustee.com> Co-authored-by: Mikhail Bragin <bangvalo@gmail.com>
2021-07-19 15:02:11 +02:00
if err != nil {
Refactor Interface package and update windows driver (#192) * script to generate syso files * test wireguard-windows driver package * set int log * add windows test * add windows test * verbose bash * use cd * move checkout * exit 0 * removed tty flag * artifact path * fix tags and add cache * fix cache * fix cache * test dir * restore artifacts in the root * try dll file * try dll file * copy dll * typo in copy dll * compile test * checkout first * updated cicd * fix add address issue and gen GUID * psexec typo * accept eula * mod tidy before tests * regular test exec and verbose test with psexec * test all * return WGInterface Interface * use WgIfaceName and timeout after 30 seconds * different ports and validate connect 2 peers * Use time.After for timeout and close interface * Use time.After for testing connect peers * WG Interface struct * Update engine and parse address * refactor Linux create and assignAddress * NewWGIface and configuration methods * Update proxy with interface methods * update up command test * resolve lint warnings * remove psexec test * close copied files * add goos before build * run tests on mac,windows and linux * cache by testing os * run on push * fix indentation * adjust test timeouts * remove parallel flag * mod tidy before test * ignore syso files * removed functions and renamed vars * different IPs for connect peers test * Generate syso with DLL * Single Close method * use port from test constant * test: remove wireguard interfaces after finishing engine test * use load_wgnt_from_rsrc Co-authored-by: braginini <bangvalo@gmail.com>
2022-01-17 14:01:58 +01:00
return wgIface, err
feature: Support live peer list update (#51) * created InitializePeer and ClosePeerConnection functions * feature: simplify peer stopping * chore: remove unused code * feature: basic management service implementation (#44) * feat: basic management service implementation [FAILING TESTS] * test: fix healthcheck test * test: #39 add peer registration endpoint test * feat: #39 add setup key handling * feat: #39 add peer management store persistence * refactor: extract config read/write to the utility package * refactor: move file contents copy to the utility package * refactor: use Accounts instead of Users in the Store * feature: add management server Docker file * refactor: introduce datadir instead of config * chore: use filepath.Join to concat filepaths instead of string concat * refactor: move stop channel to the root * refactor: move stop channel to the root * review: fix PR review notes Co-authored-by: braginini <hello@wiretrustee.com> * Handle read config file errors * feature: add letsencrypt support to the management service * fix: lint warnings * chore: change default datadir * refactor: set default flags in code not Dockerfile * chore: remove unused code * Added RemovePeer and centralized configureDevice code * remove peer from the wg interface when closing proxy * remove config file * add iface tests * fix tests, validate if file exists before removing it * removed unused functions UpdateListenPort and ConfigureWithKeyGen * Ensure we don't wait for timeout when closing * Rename ClosePeerConnection to RemovePeerConnection * Avoid returning on uapi Accept failures * Added engine tests * Remove extra add address code * Adding iface.Close * Ensure Close the interface and disable parallel test execution * check err var when listing interfaces * chore: add synchronisation to peer management * chore: add connection status to track peer connection * refactor: remove unused code Co-authored-by: braginini <hello@wiretrustee.com> Co-authored-by: Mikhail Bragin <bangvalo@gmail.com>
2021-07-19 15:02:11 +02:00
}
wgIface.address = wgAddress
Refactor Interface package and update windows driver (#192) * script to generate syso files * test wireguard-windows driver package * set int log * add windows test * add windows test * verbose bash * use cd * move checkout * exit 0 * removed tty flag * artifact path * fix tags and add cache * fix cache * fix cache * test dir * restore artifacts in the root * try dll file * try dll file * copy dll * typo in copy dll * compile test * checkout first * updated cicd * fix add address issue and gen GUID * psexec typo * accept eula * mod tidy before tests * regular test exec and verbose test with psexec * test all * return WGInterface Interface * use WgIfaceName and timeout after 30 seconds * different ports and validate connect 2 peers * Use time.After for timeout and close interface * Use time.After for testing connect peers * WG Interface struct * Update engine and parse address * refactor Linux create and assignAddress * NewWGIface and configuration methods * Update proxy with interface methods * update up command test * resolve lint warnings * remove psexec test * close copied files * add goos before build * run tests on mac,windows and linux * cache by testing os * run on push * fix indentation * adjust test timeouts * remove parallel flag * mod tidy before test * ignore syso files * removed functions and renamed vars * different IPs for connect peers test * Generate syso with DLL * Single Close method * use port from test constant * test: remove wireguard interfaces after finishing engine test * use load_wgnt_from_rsrc Co-authored-by: braginini <bangvalo@gmail.com>
2022-01-17 14:01:58 +01:00
return wgIface, nil
2021-06-24 11:46:33 +02:00
}
// Name returns the interface name
func (w *WGIface) Name() string {
return w.name
}
// Address returns the interface address
func (w *WGIface) Address() WGAddress {
return w.address
}
// Configure configures a Wireguard interface
// The interface must exist before calling this method (e.g. call interface.Create() before)
func (w *WGIface) Configure(privateKey string, port int) error {
w.mu.Lock()
defer w.mu.Unlock()
log.Debugf("configuring Wireguard interface %s", w.name)
log.Debugf("adding Wireguard private key")
key, err := wgtypes.ParseKey(privateKey)
if err != nil {
return err
}
fwmark := 0
config := wgtypes.Config{
PrivateKey: &key,
ReplacePeers: true,
FirewallMark: &fwmark,
ListenPort: &port,
}
err = w.configureDevice(config)
if err != nil {
return fmt.Errorf(`received error "%w" while configuring interface %s with port %d`, err, w.name, port)
}
return nil
}
// UpdateAddr updates address of the interface
func (w *WGIface) UpdateAddr(newAddr string) error {
w.mu.Lock()
defer w.mu.Unlock()
addr, err := parseWGAddress(newAddr)
if err != nil {
return err
}
w.address = addr
return w.assignAddr()
}
// UpdatePeer updates existing Wireguard Peer or creates a new one if doesn't exist
// Endpoint is optional
func (w *WGIface) UpdatePeer(peerKey string, allowedIps string, keepAlive time.Duration, endpoint *net.UDPAddr, preSharedKey *wgtypes.Key) error {
w.mu.Lock()
defer w.mu.Unlock()
log.Debugf("updating interface %s peer %s: endpoint %s ", w.name, peerKey, endpoint)
//parse allowed ips
_, ipNet, err := net.ParseCIDR(allowedIps)
if err != nil {
return err
}
peerKeyParsed, err := wgtypes.ParseKey(peerKey)
if err != nil {
return err
}
peer := wgtypes.PeerConfig{
PublicKey: peerKeyParsed,
ReplaceAllowedIPs: true,
AllowedIPs: []net.IPNet{*ipNet},
PersistentKeepaliveInterval: &keepAlive,
PresharedKey: preSharedKey,
Endpoint: endpoint,
}
config := wgtypes.Config{
Peers: []wgtypes.PeerConfig{peer},
}
err = w.configureDevice(config)
if err != nil {
return fmt.Errorf(`received error "%w" while updating peer on interface %s with settings: allowed ips %s, endpoint %s`, err, w.name, allowedIps, endpoint.String())
}
return nil
}
// AddAllowedIP adds a prefix to the allowed IPs list of peer
func (w *WGIface) AddAllowedIP(peerKey string, allowedIP string) error {
w.mu.Lock()
defer w.mu.Unlock()
log.Debugf("adding allowed IP to interface %s and peer %s: allowed IP %s ", w.name, peerKey, allowedIP)
_, ipNet, err := net.ParseCIDR(allowedIP)
if err != nil {
return err
}
peerKeyParsed, err := wgtypes.ParseKey(peerKey)
if err != nil {
return err
}
peer := wgtypes.PeerConfig{
PublicKey: peerKeyParsed,
UpdateOnly: true,
ReplaceAllowedIPs: false,
AllowedIPs: []net.IPNet{*ipNet},
}
config := wgtypes.Config{
Peers: []wgtypes.PeerConfig{peer},
}
err = w.configureDevice(config)
2021-06-24 11:46:33 +02:00
if err != nil {
return fmt.Errorf(`received error "%w" while adding allowed Ip to peer on interface %s with settings: allowed ips %s`, err, w.name, allowedIP)
2021-06-24 11:46:33 +02:00
}
return nil
2021-06-24 11:46:33 +02:00
}
// RemoveAllowedIP removes a prefix from the allowed IPs list of peer
func (w *WGIface) RemoveAllowedIP(peerKey string, allowedIP string) error {
w.mu.Lock()
defer w.mu.Unlock()
log.Debugf("removing allowed IP from interface %s and peer %s: allowed IP %s ", w.name, peerKey, allowedIP)
_, ipNet, err := net.ParseCIDR(allowedIP)
if err != nil {
return err
}
peerKeyParsed, err := wgtypes.ParseKey(peerKey)
if err != nil {
return err
}
existingPeer, err := getPeer(w.name, peerKey)
2021-06-24 11:46:33 +02:00
if err != nil {
return err
}
newAllowedIPs := existingPeer.AllowedIPs
for i, existingAllowedIP := range existingPeer.AllowedIPs {
if existingAllowedIP.String() == ipNet.String() {
newAllowedIPs = append(existingPeer.AllowedIPs[:i], existingPeer.AllowedIPs[i+1:]...)
break
Refactor Interface package and update windows driver (#192) * script to generate syso files * test wireguard-windows driver package * set int log * add windows test * add windows test * verbose bash * use cd * move checkout * exit 0 * removed tty flag * artifact path * fix tags and add cache * fix cache * fix cache * test dir * restore artifacts in the root * try dll file * try dll file * copy dll * typo in copy dll * compile test * checkout first * updated cicd * fix add address issue and gen GUID * psexec typo * accept eula * mod tidy before tests * regular test exec and verbose test with psexec * test all * return WGInterface Interface * use WgIfaceName and timeout after 30 seconds * different ports and validate connect 2 peers * Use time.After for timeout and close interface * Use time.After for testing connect peers * WG Interface struct * Update engine and parse address * refactor Linux create and assignAddress * NewWGIface and configuration methods * Update proxy with interface methods * update up command test * resolve lint warnings * remove psexec test * close copied files * add goos before build * run tests on mac,windows and linux * cache by testing os * run on push * fix indentation * adjust test timeouts * remove parallel flag * mod tidy before test * ignore syso files * removed functions and renamed vars * different IPs for connect peers test * Generate syso with DLL * Single Close method * use port from test constant * test: remove wireguard interfaces after finishing engine test * use load_wgnt_from_rsrc Co-authored-by: braginini <bangvalo@gmail.com>
2022-01-17 14:01:58 +01:00
}
2021-06-24 11:46:33 +02:00
}
if err != nil {
return err
}
peer := wgtypes.PeerConfig{
PublicKey: peerKeyParsed,
UpdateOnly: true,
ReplaceAllowedIPs: true,
AllowedIPs: newAllowedIPs,
}
config := wgtypes.Config{
Peers: []wgtypes.PeerConfig{peer},
}
err = w.configureDevice(config)
if err != nil {
return fmt.Errorf(`received error "%w" while removing allowed IP from peer on interface %s with settings: allowed ips %s`, err, w.name, allowedIP)
}
return nil
}
// RemovePeer removes a Wireguard Peer from the interface iface
func (w *WGIface) RemovePeer(peerKey string) error {
w.mu.Lock()
defer w.mu.Unlock()
log.Debugf("Removing peer %s from interface %s ", peerKey, w.name)
peerKeyParsed, err := wgtypes.ParseKey(peerKey)
if err != nil {
return err
}
peer := wgtypes.PeerConfig{
PublicKey: peerKeyParsed,
Remove: true,
}
config := wgtypes.Config{
Peers: []wgtypes.PeerConfig{peer},
}
err = w.configureDevice(config)
if err != nil {
return fmt.Errorf(`received error "%w" while removing peer %s from interface %s`, err, peerKey, w.name)
}
2021-06-24 11:46:33 +02:00
return nil
}
func getPeer(ifaceName, peerPubKey string) (wgtypes.Peer, error) {
wg, err := wgctrl.New()
if err != nil {
return wgtypes.Peer{}, err
}
defer func() {
err = wg.Close()
if err != nil {
log.Errorf("got error while closing wgctl: %v", err)
}
}()
wgDevice, err := wg.Device(ifaceName)
if err != nil {
return wgtypes.Peer{}, err
}
for _, peer := range wgDevice.Peers {
if peer.PublicKey.String() == peerPubKey {
return peer, nil
}
}
return wgtypes.Peer{}, fmt.Errorf("peer not found")
}
// configureDevice configures the wireguard device
func (w *WGIface) configureDevice(config wgtypes.Config) error {
wg, err := wgctrl.New()
if err != nil {
return err
}
defer wg.Close()
// validate if device with name exists
_, err = wg.Device(w.name)
if err != nil {
return err
}
log.Debugf("got Wireguard device %s", w.name)
return wg.ConfigureDevice(w.name, config)
}