2021-08-15 16:56:26 +02:00
|
|
|
package internal
|
2021-05-01 12:45:37 +02:00
|
|
|
|
|
|
|
import (
|
2021-09-07 18:36:46 +02:00
|
|
|
"context"
|
2021-05-01 12:45:37 +02:00
|
|
|
"fmt"
|
2023-05-03 14:47:44 +02:00
|
|
|
"io"
|
2022-02-08 18:03:27 +01:00
|
|
|
"math/rand"
|
2022-02-16 20:00:21 +01:00
|
|
|
"net"
|
2022-11-07 15:38:21 +01:00
|
|
|
"net/netip"
|
2022-07-07 11:24:38 +02:00
|
|
|
"reflect"
|
2022-06-23 17:04:53 +02:00
|
|
|
"runtime"
|
2022-02-08 18:03:27 +01:00
|
|
|
"strings"
|
|
|
|
"sync"
|
|
|
|
"time"
|
|
|
|
|
2023-03-03 19:49:18 +01:00
|
|
|
"github.com/pion/ice/v2"
|
|
|
|
log "github.com/sirupsen/logrus"
|
|
|
|
"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
|
|
|
|
|
2023-05-29 16:00:18 +02:00
|
|
|
"github.com/netbirdio/netbird/client/internal/acl"
|
2022-11-23 08:42:12 +01:00
|
|
|
"github.com/netbirdio/netbird/client/internal/dns"
|
2023-03-03 19:49:18 +01:00
|
|
|
"github.com/netbirdio/netbird/client/internal/peer"
|
2022-11-23 08:42:12 +01:00
|
|
|
"github.com/netbirdio/netbird/client/internal/routemanager"
|
2023-07-26 14:00:47 +02:00
|
|
|
"github.com/netbirdio/netbird/client/internal/wgproxy"
|
2022-11-23 08:42:12 +01:00
|
|
|
nbssh "github.com/netbirdio/netbird/client/ssh"
|
|
|
|
nbdns "github.com/netbirdio/netbird/dns"
|
2022-03-26 12:08:54 +01:00
|
|
|
"github.com/netbirdio/netbird/iface"
|
2023-05-03 14:47:44 +02:00
|
|
|
"github.com/netbirdio/netbird/iface/bind"
|
2022-03-26 12:08:54 +01:00
|
|
|
mgm "github.com/netbirdio/netbird/management/client"
|
|
|
|
mgmProto "github.com/netbirdio/netbird/management/proto"
|
2023-03-03 19:49:18 +01:00
|
|
|
"github.com/netbirdio/netbird/route"
|
2023-05-03 14:47:44 +02:00
|
|
|
"github.com/netbirdio/netbird/sharedsock"
|
2022-03-26 12:08:54 +01:00
|
|
|
signal "github.com/netbirdio/netbird/signal/client"
|
|
|
|
sProto "github.com/netbirdio/netbird/signal/proto"
|
|
|
|
"github.com/netbirdio/netbird/util"
|
2021-05-01 12:45:37 +02:00
|
|
|
)
|
|
|
|
|
2022-01-01 14:03:03 +01:00
|
|
|
// PeerConnectionTimeoutMax is a timeout of an initial connection attempt to a remote peer.
|
2022-02-16 20:00:21 +01:00
|
|
|
// E.g. this peer will wait PeerConnectionTimeoutMax for the remote peer to respond,
|
|
|
|
// if not successful then it will retry the connection attempt.
|
2022-01-17 14:01:58 +01:00
|
|
|
// Todo pass timeout at EnginConfig
|
2022-02-16 20:00:21 +01:00
|
|
|
const (
|
|
|
|
PeerConnectionTimeoutMax = 45000 // ms
|
|
|
|
PeerConnectionTimeoutMin = 30000 // ms
|
|
|
|
)
|
2022-01-10 18:43:13 +01:00
|
|
|
|
2022-03-08 14:47:55 +01:00
|
|
|
var ErrResetConnection = fmt.Errorf("reset connection")
|
|
|
|
|
2021-08-15 16:56:26 +02:00
|
|
|
// EngineConfig is a config for the Engine
|
|
|
|
type EngineConfig struct {
|
2022-01-17 14:01:58 +01:00
|
|
|
WgPort int
|
|
|
|
WgIfaceName string
|
2023-03-24 08:40:39 +01:00
|
|
|
|
2022-05-26 10:09:11 +02:00
|
|
|
// WgAddr is a Wireguard local address (Netbird Network IP)
|
2021-08-15 16:56:26 +02:00
|
|
|
WgAddr string
|
2022-02-16 20:00:21 +01:00
|
|
|
|
2021-08-15 16:56:26 +02:00
|
|
|
// WgPrivateKey is a Wireguard private key of our peer (it MUST never leave the machine)
|
|
|
|
WgPrivateKey wgtypes.Key
|
2022-02-16 20:00:21 +01:00
|
|
|
|
2021-08-15 16:56:26 +02:00
|
|
|
// IFaceBlackList is a list of network interfaces to ignore when discovering connection candidates (ICE related)
|
2022-11-23 11:03:29 +01:00
|
|
|
IFaceBlackList []string
|
|
|
|
DisableIPv6Discovery bool
|
2021-11-21 17:47:19 +01:00
|
|
|
|
|
|
|
PreSharedKey *wgtypes.Key
|
2022-02-16 20:00:21 +01:00
|
|
|
|
|
|
|
// UDPMuxPort default value 0 - the system will pick an available port
|
|
|
|
UDPMuxPort int
|
|
|
|
|
|
|
|
// UDPMuxSrflxPort default value 0 - the system will pick an available port
|
|
|
|
UDPMuxSrflxPort int
|
2022-06-23 17:04:53 +02:00
|
|
|
|
|
|
|
// SSHKey is a private SSH key in a PEM format
|
|
|
|
SSHKey []byte
|
2022-11-23 08:42:12 +01:00
|
|
|
|
|
|
|
NATExternalIPs []string
|
2023-01-17 19:16:50 +01:00
|
|
|
|
|
|
|
CustomDNSAddress string
|
2021-08-15 16:56:26 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// Engine is a mechanism responsible for reacting on Signal and Management stream events and managing connections to the remote peers.
|
2021-05-01 12:45:37 +02:00
|
|
|
type Engine struct {
|
2021-08-15 16:56:26 +02:00
|
|
|
// signal is a Signal Service client
|
2022-01-18 16:44:58 +01:00
|
|
|
signal signal.Client
|
2021-08-15 16:56:26 +02:00
|
|
|
// mgmClient is a Management Service client
|
2022-01-18 16:44:58 +01:00
|
|
|
mgmClient mgm.Client
|
2022-01-10 18:43:13 +01:00
|
|
|
// peerConns is a map that holds all the peers that are known to this peer
|
|
|
|
peerConns map[string]*peer.Conn
|
2021-08-15 16:56:26 +02:00
|
|
|
|
|
|
|
// syncMsgMux is used to guarantee sequential Management Service message processing
|
|
|
|
syncMsgMux *sync.Mutex
|
|
|
|
|
2023-04-17 11:15:37 +02:00
|
|
|
config *EngineConfig
|
|
|
|
mobileDep MobileDependency
|
|
|
|
|
2021-09-03 17:47:40 +02:00
|
|
|
// STUNs is a list of STUN servers used by ICE
|
|
|
|
STUNs []*ice.URL
|
|
|
|
// TURNs is a list of STUN servers used by ICE
|
|
|
|
TURNs []*ice.URL
|
2021-09-07 18:36:46 +02:00
|
|
|
|
|
|
|
cancel context.CancelFunc
|
2021-10-17 22:15:38 +02:00
|
|
|
|
|
|
|
ctx context.Context
|
2022-01-17 14:01:58 +01:00
|
|
|
|
2023-07-26 14:00:47 +02:00
|
|
|
wgInterface *iface.WGIface
|
|
|
|
wgProxyFactory *wgproxy.Factory
|
2022-01-18 16:44:58 +01:00
|
|
|
|
2023-05-03 14:47:44 +02:00
|
|
|
udpMux *bind.UniversalUDPMuxDefault
|
|
|
|
udpMuxConn io.Closer
|
2022-02-16 20:00:21 +01:00
|
|
|
|
2022-03-10 18:18:38 +01:00
|
|
|
// networkSerial is the latest CurrentSerial (state ID) of the network sent by the Management service
|
2022-01-18 16:44:58 +01:00
|
|
|
networkSerial uint64
|
2022-06-23 17:04:53 +02:00
|
|
|
|
|
|
|
sshServerFunc func(hostKeyPEM []byte, addr string) (nbssh.Server, error)
|
|
|
|
sshServer nbssh.Server
|
2022-07-02 12:02:17 +02:00
|
|
|
|
2023-03-03 19:49:18 +01:00
|
|
|
statusRecorder *peer.Status
|
2022-09-05 09:06:35 +02:00
|
|
|
|
|
|
|
routeManager routemanager.Manager
|
2023-05-29 16:00:18 +02:00
|
|
|
acl acl.Manager
|
2022-11-03 18:39:37 +01:00
|
|
|
|
2022-11-07 15:38:21 +01:00
|
|
|
dnsServer dns.Server
|
2021-05-01 12:45:37 +02:00
|
|
|
}
|
|
|
|
|
2021-05-15 12:23:56 +02:00
|
|
|
// Peer is an instance of the Connection Peer
|
2021-05-01 12:45:37 +02:00
|
|
|
type Peer struct {
|
|
|
|
WgPubKey string
|
|
|
|
WgAllowedIps string
|
|
|
|
}
|
|
|
|
|
2021-05-15 12:23:56 +02:00
|
|
|
// NewEngine creates a new Connection Engine
|
2022-02-16 20:00:21 +01:00
|
|
|
func NewEngine(
|
2022-03-08 14:47:55 +01:00
|
|
|
ctx context.Context, cancel context.CancelFunc,
|
2022-07-02 12:02:17 +02:00
|
|
|
signalClient signal.Client, mgmClient mgm.Client,
|
2023-04-17 11:15:37 +02:00
|
|
|
config *EngineConfig, mobileDep MobileDependency, statusRecorder *peer.Status,
|
2022-02-16 20:00:21 +01:00
|
|
|
) *Engine {
|
2023-07-26 14:00:47 +02:00
|
|
|
|
2021-05-01 12:45:37 +02:00
|
|
|
return &Engine{
|
2022-07-02 12:02:17 +02:00
|
|
|
ctx: ctx,
|
|
|
|
cancel: cancel,
|
|
|
|
signal: signalClient,
|
|
|
|
mgmClient: mgmClient,
|
2023-03-07 10:17:25 +01:00
|
|
|
peerConns: make(map[string]*peer.Conn),
|
2022-07-02 12:02:17 +02:00
|
|
|
syncMsgMux: &sync.Mutex{},
|
|
|
|
config: config,
|
2023-04-17 11:15:37 +02:00
|
|
|
mobileDep: mobileDep,
|
2022-07-02 12:02:17 +02:00
|
|
|
STUNs: []*ice.URL{},
|
|
|
|
TURNs: []*ice.URL{},
|
|
|
|
networkSerial: 0,
|
|
|
|
sshServerFunc: nbssh.DefaultSSHServer,
|
|
|
|
statusRecorder: statusRecorder,
|
2023-07-26 14:00:47 +02:00
|
|
|
wgProxyFactory: wgproxy.NewFactory(config.WgPort),
|
2021-09-07 18:36:46 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (e *Engine) Stop() error {
|
2022-01-10 18:43:13 +01:00
|
|
|
e.syncMsgMux.Lock()
|
|
|
|
defer e.syncMsgMux.Unlock()
|
|
|
|
|
2022-01-25 11:18:01 +01:00
|
|
|
err := e.removeAllPeers()
|
2021-10-17 22:15:38 +02:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2022-03-13 15:16:16 +01:00
|
|
|
// very ugly but we want to remove peers from the WireGuard interface first before removing interface.
|
|
|
|
// Removing peers happens in the conn.CLose() asynchronously
|
|
|
|
time.Sleep(500 * time.Millisecond)
|
|
|
|
|
2023-02-21 10:46:58 +01:00
|
|
|
e.close()
|
2022-05-26 10:09:11 +02:00
|
|
|
log.Infof("stopped Netbird Engine")
|
2021-09-07 18:36:46 +02:00
|
|
|
return nil
|
2021-05-01 12:45:37 +02:00
|
|
|
}
|
|
|
|
|
2023-04-13 17:00:01 +02:00
|
|
|
// Start creates a new WireGuard tunnel interface and listens to events from Signal and Management services
|
2021-08-15 16:56:26 +02:00
|
|
|
// Connections to remote peers are not established here.
|
|
|
|
// However, they will be established once an event with a list of peers to connect to will be received from Management Service
|
|
|
|
func (e *Engine) Start() error {
|
2022-01-10 18:43:13 +01:00
|
|
|
e.syncMsgMux.Lock()
|
|
|
|
defer e.syncMsgMux.Unlock()
|
2021-08-15 16:56:26 +02:00
|
|
|
|
2023-04-13 17:00:01 +02:00
|
|
|
wgIFaceName := e.config.WgIfaceName
|
2021-08-15 16:56:26 +02:00
|
|
|
wgAddr := e.config.WgAddr
|
|
|
|
myPrivateKey := e.config.WgPrivateKey
|
2022-01-17 14:01:58 +01:00
|
|
|
var err error
|
2023-03-24 08:40:39 +01:00
|
|
|
transportNet, err := e.newStdNet()
|
|
|
|
if err != nil {
|
2023-04-13 17:00:01 +02:00
|
|
|
log.Errorf("failed to create pion's stdnet: %s", err)
|
2022-02-16 20:00:21 +01:00
|
|
|
}
|
2023-05-31 18:25:24 +02:00
|
|
|
|
|
|
|
e.wgInterface, err = iface.NewWGIFace(wgIFaceName, wgAddr, iface.DefaultMTU, e.mobileDep.TunAdapter, transportNet)
|
2022-02-16 20:00:21 +01:00
|
|
|
if err != nil {
|
2023-04-13 17:00:01 +02:00
|
|
|
log.Errorf("failed creating wireguard interface instance %s: [%s]", wgIFaceName, err.Error())
|
2022-02-16 20:00:21 +01:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2023-06-12 14:43:55 +02:00
|
|
|
var routes []*route.Route
|
|
|
|
|
|
|
|
if runtime.GOOS == "android" {
|
2023-07-14 21:56:22 +02:00
|
|
|
routes, err = e.readInitialSettings()
|
2023-06-12 14:43:55 +02:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2023-07-14 21:56:22 +02:00
|
|
|
if e.dnsServer == nil {
|
|
|
|
e.dnsServer = dns.NewDefaultServerPermanentUpstream(e.ctx, e.wgInterface, e.mobileDep.HostDNSAddresses)
|
|
|
|
go e.mobileDep.DnsReadyListener.OnReady()
|
|
|
|
}
|
|
|
|
} else {
|
2023-06-12 14:43:55 +02:00
|
|
|
// todo fix custom address
|
2023-07-14 21:56:22 +02:00
|
|
|
if e.dnsServer == nil {
|
|
|
|
e.dnsServer, err = dns.NewDefaultServer(e.ctx, e.wgInterface, e.config.CustomDNSAddress)
|
|
|
|
if err != nil {
|
|
|
|
e.close()
|
|
|
|
return err
|
|
|
|
}
|
2023-06-12 14:43:55 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-05-31 18:25:24 +02:00
|
|
|
e.routeManager = routemanager.NewManager(e.ctx, e.config.WgPrivateKey.PublicKey().String(), e.wgInterface, e.statusRecorder, routes)
|
|
|
|
e.routeManager.SetRouteChangeListener(e.mobileDep.RouteListener)
|
|
|
|
|
2023-06-12 14:43:55 +02:00
|
|
|
if runtime.GOOS != "android" {
|
|
|
|
err = e.wgInterface.Create()
|
|
|
|
} else {
|
|
|
|
err = e.wgInterface.CreateOnMobile(iface.MobileIFaceArguments{
|
|
|
|
Routes: e.routeManager.InitialRouteRange(),
|
|
|
|
Dns: e.dnsServer.DnsIP(),
|
|
|
|
})
|
|
|
|
}
|
2021-05-01 12:45:37 +02:00
|
|
|
if err != nil {
|
2023-04-13 17:00:01 +02:00
|
|
|
log.Errorf("failed creating tunnel interface %s: [%s]", wgIFaceName, err.Error())
|
2023-02-21 10:46:58 +01:00
|
|
|
e.close()
|
2021-05-01 12:45:37 +02:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2022-01-17 14:01:58 +01:00
|
|
|
err = e.wgInterface.Configure(myPrivateKey.String(), e.config.WgPort)
|
2021-05-01 12:45:37 +02:00
|
|
|
if err != nil {
|
2023-04-13 17:00:01 +02:00
|
|
|
log.Errorf("failed configuring Wireguard interface [%s]: %s", wgIFaceName, err.Error())
|
2023-02-21 10:46:58 +01:00
|
|
|
e.close()
|
2021-05-01 12:45:37 +02:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2023-04-13 17:00:01 +02:00
|
|
|
if e.wgInterface.IsUserspaceBind() {
|
|
|
|
iceBind := e.wgInterface.GetBind()
|
|
|
|
udpMux, err := iceBind.GetICEMux()
|
|
|
|
if err != nil {
|
|
|
|
e.close()
|
|
|
|
return err
|
|
|
|
}
|
2023-05-03 14:47:44 +02:00
|
|
|
e.udpMux = udpMux
|
2023-04-13 17:00:01 +02:00
|
|
|
log.Infof("using userspace bind mode %s", udpMux.LocalAddr().String())
|
|
|
|
} else {
|
2023-05-04 12:28:32 +02:00
|
|
|
rawSock, err := sharedsock.Listen(e.config.WgPort, sharedsock.NewIncomingSTUNFilter())
|
2023-04-13 17:00:01 +02:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2023-05-03 14:47:44 +02:00
|
|
|
mux := bind.NewUniversalUDPMuxDefault(bind.UniversalUDPMuxParams{UDPConn: rawSock, Net: transportNet})
|
|
|
|
go mux.ReadFromConn(e.ctx)
|
|
|
|
e.udpMuxConn = rawSock
|
|
|
|
e.udpMux = mux
|
2023-04-13 17:00:01 +02:00
|
|
|
}
|
|
|
|
|
2023-05-29 16:00:18 +02:00
|
|
|
if acl, err := acl.Create(e.wgInterface); err != nil {
|
|
|
|
log.Errorf("failed to create ACL manager, policy will not work: %s", err.Error())
|
|
|
|
} else {
|
|
|
|
e.acl = acl
|
|
|
|
}
|
|
|
|
|
2023-06-15 12:25:18 +02:00
|
|
|
err = e.dnsServer.Initialize()
|
|
|
|
if err != nil {
|
|
|
|
e.close()
|
|
|
|
return err
|
2023-06-13 09:20:29 +02:00
|
|
|
}
|
|
|
|
|
2021-08-15 16:56:26 +02:00
|
|
|
e.receiveSignalEvents()
|
|
|
|
e.receiveManagementEvents()
|
2021-05-01 12:45:37 +02:00
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2022-06-04 19:41:01 +02:00
|
|
|
// modifyPeers updates peers that have been modified (e.g. IP address has been changed).
|
|
|
|
// It closes the existing connection, removes it from the peerConns map, and creates a new one.
|
|
|
|
func (e *Engine) modifyPeers(peersUpdate []*mgmProto.RemotePeerConfig) error {
|
|
|
|
|
|
|
|
// first, check if peers have been modified
|
|
|
|
var modified []*mgmProto.RemotePeerConfig
|
|
|
|
for _, p := range peersUpdate {
|
2022-11-26 13:29:50 +01:00
|
|
|
peerPubKey := p.GetWgPubKey()
|
|
|
|
if peerConn, ok := e.peerConns[peerPubKey]; ok {
|
2023-07-26 14:00:47 +02:00
|
|
|
if peerConn.WgConfig().AllowedIps != strings.Join(p.AllowedIps, ",") {
|
2022-06-04 19:41:01 +02:00
|
|
|
modified = append(modified, p)
|
2022-11-26 13:29:50 +01:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
err := e.statusRecorder.UpdatePeerFQDN(peerPubKey, p.GetFqdn())
|
|
|
|
if err != nil {
|
|
|
|
log.Warnf("error updating peer's %s fqdn in the status recorder, got error: %v", peerPubKey, err)
|
2022-06-04 19:41:01 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// second, close all modified connections and remove them from the state map
|
|
|
|
for _, p := range modified {
|
|
|
|
err := e.removePeer(p.GetWgPubKey())
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
// third, add the peer connections again
|
|
|
|
for _, p := range modified {
|
|
|
|
err := e.addNewPeer(p)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// removePeers finds and removes peers that do not exist anymore in the network map received from the Management Service.
|
|
|
|
// It also removes peers that have been modified (e.g. change of IP address). They will be added again in addPeers method.
|
2022-01-18 16:44:58 +01:00
|
|
|
func (e *Engine) removePeers(peersUpdate []*mgmProto.RemotePeerConfig) error {
|
|
|
|
currentPeers := make([]string, 0, len(e.peerConns))
|
|
|
|
for p := range e.peerConns {
|
|
|
|
currentPeers = append(currentPeers, p)
|
|
|
|
}
|
|
|
|
|
|
|
|
newPeers := make([]string, 0, len(peersUpdate))
|
|
|
|
for _, p := range peersUpdate {
|
|
|
|
newPeers = append(newPeers, p.GetWgPubKey())
|
|
|
|
}
|
|
|
|
|
|
|
|
toRemove := util.SliceDiff(currentPeers, newPeers)
|
|
|
|
|
|
|
|
for _, p := range toRemove {
|
2022-01-10 18:43:13 +01:00
|
|
|
err := e.removePeer(p)
|
2021-08-15 16:56:26 +02:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2022-01-10 18:43:13 +01:00
|
|
|
log.Infof("removed peer %s", p)
|
2021-08-15 16:56:26 +02:00
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2022-01-18 16:44:58 +01:00
|
|
|
func (e *Engine) removeAllPeers() error {
|
2021-10-17 22:15:38 +02:00
|
|
|
log.Debugf("removing all peer connections")
|
2022-01-10 18:43:13 +01:00
|
|
|
for p := range e.peerConns {
|
|
|
|
err := e.removePeer(p)
|
2021-10-17 22:15:38 +02:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2022-06-23 17:04:53 +02:00
|
|
|
// removePeer closes an existing peer connection, removes a peer, and clears authorized key of the SSH server
|
2021-12-31 18:11:33 +01:00
|
|
|
func (e *Engine) removePeer(peerKey string) error {
|
2022-01-10 18:43:13 +01:00
|
|
|
log.Debugf("removing peer from engine %s", peerKey)
|
2022-06-23 17:04:53 +02:00
|
|
|
|
2022-07-07 11:24:38 +02:00
|
|
|
if !isNil(e.sshServer) {
|
2022-06-23 17:04:53 +02:00
|
|
|
e.sshServer.RemoveAuthorizedKey(peerKey)
|
|
|
|
}
|
|
|
|
|
2022-07-05 19:47:50 +02:00
|
|
|
defer func() {
|
2022-07-02 12:02:17 +02:00
|
|
|
err := e.statusRecorder.RemovePeer(peerKey)
|
|
|
|
if err != nil {
|
2022-07-05 19:47:50 +02:00
|
|
|
log.Warnf("received error when removing peer %s from status recorder: %v", peerKey, err)
|
2022-07-02 12:02:17 +02:00
|
|
|
}
|
2022-07-05 19:47:50 +02:00
|
|
|
}()
|
2022-07-02 12:02:17 +02:00
|
|
|
|
2022-07-05 19:47:50 +02:00
|
|
|
conn, exists := e.peerConns[peerKey]
|
|
|
|
if exists {
|
2022-01-10 18:43:13 +01:00
|
|
|
delete(e.peerConns, peerKey)
|
2022-07-05 19:47:50 +02:00
|
|
|
err := conn.Close()
|
2022-01-21 13:52:19 +01:00
|
|
|
if err != nil {
|
|
|
|
switch err.(type) {
|
|
|
|
case *peer.ConnectionAlreadyClosedError:
|
|
|
|
return nil
|
|
|
|
default:
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
2021-07-19 15:02:11 +02:00
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2022-01-18 16:44:58 +01:00
|
|
|
func signalCandidate(candidate ice.Candidate, myKey wgtypes.Key, remoteKey wgtypes.Key, s signal.Client) error {
|
2021-05-01 12:45:37 +02:00
|
|
|
err := s.Send(&sProto.Message{
|
|
|
|
Key: myKey.PublicKey().String(),
|
|
|
|
RemoteKey: remoteKey.String(),
|
2021-05-01 18:29:59 +02:00
|
|
|
Body: &sProto.Body{
|
|
|
|
Type: sProto.Body_CANDIDATE,
|
|
|
|
Payload: candidate.Marshal(),
|
|
|
|
},
|
2021-05-01 12:45:37 +02:00
|
|
|
})
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2023-03-16 16:46:17 +01:00
|
|
|
func sendSignal(message *sProto.Message, s signal.Client) error {
|
|
|
|
return s.Send(message)
|
|
|
|
}
|
|
|
|
|
2022-09-02 19:33:35 +02:00
|
|
|
// SignalOfferAnswer signals either an offer or an answer to remote peer
|
|
|
|
func SignalOfferAnswer(offerAnswer peer.OfferAnswer, myKey wgtypes.Key, remoteKey wgtypes.Key, s signal.Client, isAnswer bool) error {
|
2021-05-01 18:29:59 +02:00
|
|
|
var t sProto.Body_Type
|
2021-05-01 12:45:37 +02:00
|
|
|
if isAnswer {
|
2021-05-01 18:29:59 +02:00
|
|
|
t = sProto.Body_ANSWER
|
2021-05-01 12:45:37 +02:00
|
|
|
} else {
|
2021-05-01 18:29:59 +02:00
|
|
|
t = sProto.Body_OFFER
|
2021-05-01 12:45:37 +02:00
|
|
|
}
|
|
|
|
|
2022-09-02 19:33:35 +02:00
|
|
|
msg, err := signal.MarshalCredential(myKey, offerAnswer.WgListenPort, remoteKey, &signal.Credential{
|
|
|
|
UFrag: offerAnswer.IceCredentials.UFrag,
|
|
|
|
Pwd: offerAnswer.IceCredentials.Pwd,
|
2022-02-16 20:00:21 +01:00
|
|
|
}, t)
|
2021-05-15 12:23:56 +02:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2023-03-16 16:46:17 +01:00
|
|
|
|
2021-05-01 18:29:59 +02:00
|
|
|
err = s.Send(msg)
|
2021-05-01 12:45:37 +02:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2022-01-18 16:44:58 +01:00
|
|
|
func (e *Engine) handleSync(update *mgmProto.SyncResponse) error {
|
|
|
|
e.syncMsgMux.Lock()
|
|
|
|
defer e.syncMsgMux.Unlock()
|
|
|
|
|
|
|
|
if update.GetWiretrusteeConfig() != nil {
|
|
|
|
err := e.updateTURNs(update.GetWiretrusteeConfig().GetTurns())
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
err = e.updateSTUNs(update.GetWiretrusteeConfig().GetStuns())
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2022-02-16 20:00:21 +01:00
|
|
|
// todo update signal
|
2022-01-18 16:44:58 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
if update.GetNetworkMap() != nil {
|
|
|
|
// only apply new changes and ignore old ones
|
|
|
|
err := e.updateNetworkMap(update.GetNetworkMap())
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2022-07-07 11:24:38 +02:00
|
|
|
func isNil(server nbssh.Server) bool {
|
|
|
|
return server == nil || reflect.ValueOf(server).IsNil()
|
|
|
|
}
|
|
|
|
|
2022-06-23 17:04:53 +02:00
|
|
|
func (e *Engine) updateSSH(sshConf *mgmProto.SSHConfig) error {
|
|
|
|
if sshConf.GetSshEnabled() {
|
|
|
|
if runtime.GOOS == "windows" {
|
|
|
|
log.Warnf("running SSH server on Windows is not supported")
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
// start SSH server if it wasn't running
|
2022-07-07 11:24:38 +02:00
|
|
|
if isNil(e.sshServer) {
|
2022-06-23 17:04:53 +02:00
|
|
|
//nil sshServer means it has not yet been started
|
|
|
|
var err error
|
|
|
|
e.sshServer, err = e.sshServerFunc(e.config.SSHKey,
|
2023-02-13 18:34:56 +01:00
|
|
|
fmt.Sprintf("%s:%d", e.wgInterface.Address().IP.String(), nbssh.DefaultSSHPort))
|
2022-06-23 17:04:53 +02:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
go func() {
|
|
|
|
// blocking
|
|
|
|
err = e.sshServer.Start()
|
|
|
|
if err != nil {
|
|
|
|
// will throw error when we stop it even if it is a graceful stop
|
|
|
|
log.Debugf("stopped SSH server with error %v", err)
|
|
|
|
}
|
|
|
|
e.syncMsgMux.Lock()
|
|
|
|
defer e.syncMsgMux.Unlock()
|
|
|
|
e.sshServer = nil
|
|
|
|
log.Infof("stopped SSH server")
|
|
|
|
}()
|
|
|
|
} else {
|
|
|
|
log.Debugf("SSH server is already running")
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
// Disable SSH server request, so stop it if it was running
|
2022-07-07 11:24:38 +02:00
|
|
|
if !isNil(e.sshServer) {
|
2022-06-23 17:04:53 +02:00
|
|
|
err := e.sshServer.Stop()
|
|
|
|
if err != nil {
|
|
|
|
log.Warnf("failed to stop SSH server %v", err)
|
|
|
|
}
|
|
|
|
e.sshServer = nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2022-06-04 19:41:01 +02:00
|
|
|
func (e *Engine) updateConfig(conf *mgmProto.PeerConfig) error {
|
2023-02-13 18:34:56 +01:00
|
|
|
if e.wgInterface.Address().String() != conf.Address {
|
|
|
|
oldAddr := e.wgInterface.Address().String()
|
2022-06-04 19:41:01 +02:00
|
|
|
log.Debugf("updating peer address from %s to %s", oldAddr, conf.Address)
|
|
|
|
err := e.wgInterface.UpdateAddr(conf.Address)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2022-06-23 17:04:53 +02:00
|
|
|
e.config.WgAddr = conf.Address
|
2022-06-04 19:41:01 +02:00
|
|
|
log.Infof("updated peer address from %s to %s", oldAddr, conf.Address)
|
|
|
|
}
|
|
|
|
|
2022-06-23 17:04:53 +02:00
|
|
|
if conf.GetSshConfig() != nil {
|
|
|
|
err := e.updateSSH(conf.GetSshConfig())
|
|
|
|
if err != nil {
|
|
|
|
log.Warnf("failed handling SSH server setup %v", e)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-03-03 19:49:18 +01:00
|
|
|
e.statusRecorder.UpdateLocalPeerState(peer.LocalPeerState{
|
2022-11-26 13:29:50 +01:00
|
|
|
IP: e.config.WgAddr,
|
|
|
|
PubKey: e.config.WgPrivateKey.PublicKey().String(),
|
2023-04-13 17:00:01 +02:00
|
|
|
KernelInterface: iface.WireGuardModuleIsLoaded(),
|
2022-11-26 13:29:50 +01:00
|
|
|
FQDN: conf.GetFqdn(),
|
|
|
|
})
|
|
|
|
|
2022-06-04 19:41:01 +02:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2021-08-15 16:56:26 +02:00
|
|
|
// receiveManagementEvents connects to the Management Service event stream to receive updates from the management service
|
|
|
|
// E.g. when a new peer has been registered and we are allowed to connect to it.
|
|
|
|
func (e *Engine) receiveManagementEvents() {
|
2021-09-07 18:36:46 +02:00
|
|
|
go func() {
|
|
|
|
err := e.mgmClient.Sync(func(update *mgmProto.SyncResponse) error {
|
2022-01-18 16:44:58 +01:00
|
|
|
return e.handleSync(update)
|
2021-09-07 18:36:46 +02:00
|
|
|
})
|
2021-09-03 17:47:40 +02:00
|
|
|
if err != nil {
|
2021-11-06 15:00:13 +01:00
|
|
|
// happens if management is unavailable for a long time.
|
|
|
|
// We want to cancel the operation of the whole client
|
2022-03-08 14:47:55 +01:00
|
|
|
_ = CtxGetState(e.ctx).Wrap(ErrResetConnection)
|
2021-09-07 18:36:46 +02:00
|
|
|
e.cancel()
|
|
|
|
return
|
2021-08-15 16:56:26 +02:00
|
|
|
}
|
2021-10-17 22:15:38 +02:00
|
|
|
log.Debugf("stopped receiving updates from Management Service")
|
2021-09-07 18:36:46 +02:00
|
|
|
}()
|
|
|
|
log.Debugf("connecting to Management Service updates stream")
|
2021-08-15 16:56:26 +02:00
|
|
|
}
|
|
|
|
|
2021-09-03 17:47:40 +02:00
|
|
|
func (e *Engine) updateSTUNs(stuns []*mgmProto.HostConfig) error {
|
|
|
|
if len(stuns) == 0 {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
var newSTUNs []*ice.URL
|
|
|
|
log.Debugf("got STUNs update from Management Service, updating")
|
|
|
|
for _, stun := range stuns {
|
|
|
|
url, err := ice.ParseURL(stun.Uri)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
newSTUNs = append(newSTUNs, url)
|
|
|
|
}
|
|
|
|
e.STUNs = newSTUNs
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (e *Engine) updateTURNs(turns []*mgmProto.ProtectedHostConfig) error {
|
|
|
|
if len(turns) == 0 {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
var newTURNs []*ice.URL
|
|
|
|
log.Debugf("got TURNs update from Management Service, updating")
|
|
|
|
for _, turn := range turns {
|
|
|
|
url, err := ice.ParseURL(turn.HostConfig.Uri)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
url.Username = turn.User
|
|
|
|
url.Password = turn.Password
|
|
|
|
newTURNs = append(newTURNs, url)
|
|
|
|
}
|
|
|
|
e.TURNs = newTURNs
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2022-01-18 16:44:58 +01:00
|
|
|
func (e *Engine) updateNetworkMap(networkMap *mgmProto.NetworkMap) error {
|
2022-06-23 17:04:53 +02:00
|
|
|
|
|
|
|
// intentionally leave it before checking serial because for now it can happen that peer IP changed but serial didn't
|
|
|
|
if networkMap.GetPeerConfig() != nil {
|
|
|
|
err := e.updateConfig(networkMap.GetPeerConfig())
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-01-18 16:44:58 +01:00
|
|
|
serial := networkMap.GetSerial()
|
|
|
|
if e.networkSerial > serial {
|
|
|
|
log.Debugf("received outdated NetworkMap with serial %d, ignoring", serial)
|
|
|
|
return nil
|
2021-09-03 17:47:40 +02:00
|
|
|
}
|
|
|
|
|
2022-01-18 16:44:58 +01:00
|
|
|
log.Debugf("got peers update from Management Service, total peers to connect to = %d", len(networkMap.GetRemotePeers()))
|
|
|
|
|
2023-03-07 10:17:25 +01:00
|
|
|
e.updateOfflinePeers(networkMap.GetOfflinePeers())
|
|
|
|
|
2022-01-18 16:44:58 +01:00
|
|
|
// cleanup request, most likely our peer has been deleted
|
|
|
|
if networkMap.GetRemotePeersIsEmpty() {
|
|
|
|
err := e.removeAllPeers()
|
2023-06-19 11:20:34 +02:00
|
|
|
e.statusRecorder.FinishPeerListModifications()
|
2022-01-18 16:44:58 +01:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
err := e.removePeers(networkMap.GetRemotePeers())
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2022-06-04 19:41:01 +02:00
|
|
|
err = e.modifyPeers(networkMap.GetRemotePeers())
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2022-01-18 16:44:58 +01:00
|
|
|
err = e.addNewPeers(networkMap.GetRemotePeers())
|
|
|
|
if err != nil {
|
|
|
|
return err
|
2021-09-03 17:47:40 +02:00
|
|
|
}
|
2022-06-23 17:04:53 +02:00
|
|
|
|
2023-06-19 11:20:34 +02:00
|
|
|
e.statusRecorder.FinishPeerListModifications()
|
|
|
|
|
2022-06-23 17:04:53 +02:00
|
|
|
// update SSHServer by adding remote peer SSH keys
|
2022-07-07 11:24:38 +02:00
|
|
|
if !isNil(e.sshServer) {
|
2022-06-23 17:04:53 +02:00
|
|
|
for _, config := range networkMap.GetRemotePeers() {
|
|
|
|
if config.GetSshConfig() != nil && config.GetSshConfig().GetSshPubKey() != nil {
|
|
|
|
err := e.sshServer.AddAuthorizedKey(config.WgPubKey, string(config.GetSshConfig().GetSshPubKey()))
|
|
|
|
if err != nil {
|
|
|
|
log.Warnf("failed adding authroized key to SSH DefaultServer %v", err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2021-09-03 17:47:40 +02:00
|
|
|
}
|
2022-09-05 09:06:35 +02:00
|
|
|
protoRoutes := networkMap.GetRoutes()
|
|
|
|
if protoRoutes == nil {
|
|
|
|
protoRoutes = []*mgmProto.Route{}
|
|
|
|
}
|
|
|
|
err := e.routeManager.UpdateRoutes(serial, toRoutes(protoRoutes))
|
|
|
|
if err != nil {
|
|
|
|
log.Errorf("failed to update routes, err: %v", err)
|
|
|
|
}
|
2021-09-03 17:47:40 +02:00
|
|
|
|
2022-11-07 15:38:21 +01:00
|
|
|
protoDNSConfig := networkMap.GetDNSConfig()
|
|
|
|
if protoDNSConfig == nil {
|
|
|
|
protoDNSConfig = &mgmProto.DNSConfig{}
|
|
|
|
}
|
2023-03-17 10:37:27 +01:00
|
|
|
|
2022-11-07 15:38:21 +01:00
|
|
|
err = e.dnsServer.UpdateDNSServer(serial, toDNSConfig(protoDNSConfig))
|
|
|
|
if err != nil {
|
|
|
|
log.Errorf("failed to update dns server, err: %v", err)
|
|
|
|
}
|
|
|
|
|
2023-05-29 16:00:18 +02:00
|
|
|
if e.acl != nil {
|
2023-06-02 08:14:47 +02:00
|
|
|
e.acl.ApplyFiltering(networkMap)
|
2023-05-29 16:00:18 +02:00
|
|
|
}
|
2022-01-18 16:44:58 +01:00
|
|
|
e.networkSerial = serial
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2022-09-05 09:06:35 +02:00
|
|
|
func toRoutes(protoRoutes []*mgmProto.Route) []*route.Route {
|
|
|
|
routes := make([]*route.Route, 0)
|
|
|
|
for _, protoRoute := range protoRoutes {
|
|
|
|
_, prefix, _ := route.ParseNetwork(protoRoute.Network)
|
|
|
|
convertedRoute := &route.Route{
|
|
|
|
ID: protoRoute.ID,
|
|
|
|
Network: prefix,
|
|
|
|
NetID: protoRoute.NetID,
|
|
|
|
NetworkType: route.NetworkType(protoRoute.NetworkType),
|
|
|
|
Peer: protoRoute.Peer,
|
|
|
|
Metric: int(protoRoute.Metric),
|
|
|
|
Masquerade: protoRoute.Masquerade,
|
|
|
|
}
|
|
|
|
routes = append(routes, convertedRoute)
|
|
|
|
}
|
|
|
|
return routes
|
|
|
|
}
|
|
|
|
|
2022-11-07 15:38:21 +01:00
|
|
|
func toDNSConfig(protoDNSConfig *mgmProto.DNSConfig) nbdns.Config {
|
|
|
|
dnsUpdate := nbdns.Config{
|
|
|
|
ServiceEnable: protoDNSConfig.GetServiceEnable(),
|
|
|
|
CustomZones: make([]nbdns.CustomZone, 0),
|
|
|
|
NameServerGroups: make([]*nbdns.NameServerGroup, 0),
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, zone := range protoDNSConfig.GetCustomZones() {
|
|
|
|
dnsZone := nbdns.CustomZone{
|
|
|
|
Domain: zone.GetDomain(),
|
|
|
|
}
|
|
|
|
for _, record := range zone.Records {
|
|
|
|
dnsRecord := nbdns.SimpleRecord{
|
|
|
|
Name: record.GetName(),
|
|
|
|
Type: int(record.GetType()),
|
|
|
|
Class: record.GetClass(),
|
|
|
|
TTL: int(record.GetTTL()),
|
|
|
|
RData: record.GetRData(),
|
|
|
|
}
|
|
|
|
dnsZone.Records = append(dnsZone.Records, dnsRecord)
|
|
|
|
}
|
|
|
|
dnsUpdate.CustomZones = append(dnsUpdate.CustomZones, dnsZone)
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, nsGroup := range protoDNSConfig.GetNameServerGroups() {
|
|
|
|
dnsNSGroup := &nbdns.NameServerGroup{
|
|
|
|
Primary: nsGroup.GetPrimary(),
|
|
|
|
Domains: nsGroup.GetDomains(),
|
|
|
|
}
|
|
|
|
for _, ns := range nsGroup.GetNameServers() {
|
|
|
|
dnsNS := nbdns.NameServer{
|
|
|
|
IP: netip.MustParseAddr(ns.GetIP()),
|
|
|
|
NSType: nbdns.NameServerType(ns.GetNSType()),
|
|
|
|
Port: int(ns.GetPort()),
|
|
|
|
}
|
|
|
|
dnsNSGroup.NameServers = append(dnsNSGroup.NameServers, dnsNS)
|
|
|
|
}
|
|
|
|
dnsUpdate.NameServerGroups = append(dnsUpdate.NameServerGroups, dnsNSGroup)
|
|
|
|
}
|
|
|
|
return dnsUpdate
|
|
|
|
}
|
|
|
|
|
2023-03-07 10:17:25 +01:00
|
|
|
func (e *Engine) updateOfflinePeers(offlinePeers []*mgmProto.RemotePeerConfig) {
|
|
|
|
replacement := make([]peer.State, len(offlinePeers))
|
|
|
|
for i, offlinePeer := range offlinePeers {
|
|
|
|
log.Debugf("added offline peer %s", offlinePeer.Fqdn)
|
|
|
|
replacement[i] = peer.State{
|
|
|
|
IP: strings.Join(offlinePeer.GetAllowedIps(), ","),
|
|
|
|
PubKey: offlinePeer.GetWgPubKey(),
|
|
|
|
FQDN: offlinePeer.GetFqdn(),
|
|
|
|
ConnStatus: peer.StatusDisconnected,
|
|
|
|
ConnStatusUpdate: time.Now(),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
e.statusRecorder.ReplaceOfflinePeers(replacement)
|
|
|
|
}
|
|
|
|
|
2022-06-04 19:41:01 +02:00
|
|
|
// addNewPeers adds peers that were not know before but arrived from the Management service with the update
|
2022-01-18 16:44:58 +01:00
|
|
|
func (e *Engine) addNewPeers(peersUpdate []*mgmProto.RemotePeerConfig) error {
|
|
|
|
for _, p := range peersUpdate {
|
2022-06-04 19:41:01 +02:00
|
|
|
err := e.addNewPeer(p)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
2022-01-10 18:43:13 +01:00
|
|
|
|
2022-06-04 19:41:01 +02:00
|
|
|
// addNewPeer add peer if connection doesn't exist
|
|
|
|
func (e *Engine) addNewPeer(peerConfig *mgmProto.RemotePeerConfig) error {
|
|
|
|
peerKey := peerConfig.GetWgPubKey()
|
|
|
|
peerIPs := peerConfig.GetAllowedIps()
|
|
|
|
if _, ok := e.peerConns[peerKey]; !ok {
|
|
|
|
conn, err := e.createPeerConn(peerKey, strings.Join(peerIPs, ","))
|
|
|
|
if err != nil {
|
|
|
|
return err
|
2021-09-03 17:47:40 +02:00
|
|
|
}
|
2022-06-04 19:41:01 +02:00
|
|
|
e.peerConns[peerKey] = conn
|
2021-09-03 17:47:40 +02:00
|
|
|
|
2023-06-19 11:20:34 +02:00
|
|
|
err = e.statusRecorder.AddPeer(peerKey, peerConfig.Fqdn)
|
2022-07-02 12:02:17 +02:00
|
|
|
if err != nil {
|
|
|
|
log.Warnf("error adding peer %s to status recorder, got error: %v", peerKey, err)
|
|
|
|
}
|
|
|
|
|
2022-06-04 19:41:01 +02:00
|
|
|
go e.connWorker(conn, peerKey)
|
2021-09-03 17:47:40 +02:00
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2022-07-21 22:07:38 +02:00
|
|
|
func (e *Engine) connWorker(conn *peer.Conn, peerKey string) {
|
2022-01-10 18:43:13 +01:00
|
|
|
for {
|
|
|
|
|
|
|
|
// randomize starting time a bit
|
|
|
|
min := 500
|
|
|
|
max := 2000
|
|
|
|
time.Sleep(time.Duration(rand.Intn(max-min)+min) * time.Millisecond)
|
|
|
|
|
|
|
|
// if peer has been removed -> give up
|
|
|
|
if !e.peerExists(peerKey) {
|
2022-03-13 15:16:16 +01:00
|
|
|
log.Debugf("peer %s doesn't exist anymore, won't retry connection", peerKey)
|
2022-01-10 18:43:13 +01:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
if !e.signal.Ready() {
|
|
|
|
log.Infof("signal client isn't ready, skipping connection attempt %s", peerKey)
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2022-07-21 22:07:38 +02:00
|
|
|
// we might have received new STUN and TURN servers meanwhile, so update them
|
|
|
|
e.syncMsgMux.Lock()
|
2023-07-26 14:00:47 +02:00
|
|
|
conn.UpdateStunTurn(append(e.STUNs, e.TURNs...))
|
2022-07-21 22:07:38 +02:00
|
|
|
e.syncMsgMux.Unlock()
|
|
|
|
|
2022-01-10 18:43:13 +01:00
|
|
|
err := conn.Open()
|
|
|
|
if err != nil {
|
|
|
|
log.Debugf("connection to peer %s failed: %v", peerKey, err)
|
2022-06-04 19:41:01 +02:00
|
|
|
switch err.(type) {
|
|
|
|
case *peer.ConnectionClosedError:
|
|
|
|
// conn has been forced to close, so we exit the loop
|
|
|
|
return
|
|
|
|
default:
|
|
|
|
}
|
2022-01-10 18:43:13 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-06-05 15:34:22 +02:00
|
|
|
func (e *Engine) peerExists(peerKey string) bool {
|
2022-01-10 18:43:13 +01:00
|
|
|
e.syncMsgMux.Lock()
|
|
|
|
defer e.syncMsgMux.Unlock()
|
|
|
|
_, ok := e.peerConns[peerKey]
|
|
|
|
return ok
|
|
|
|
}
|
|
|
|
|
2023-06-05 15:34:22 +02:00
|
|
|
func (e *Engine) createPeerConn(pubKey string, allowedIPs string) (*peer.Conn, error) {
|
2022-08-22 12:21:19 +02:00
|
|
|
log.Debugf("creating peer connection %s", pubKey)
|
2022-01-10 18:43:13 +01:00
|
|
|
var stunTurn []*ice.URL
|
|
|
|
stunTurn = append(stunTurn, e.STUNs...)
|
|
|
|
stunTurn = append(stunTurn, e.TURNs...)
|
|
|
|
|
2023-07-26 14:00:47 +02:00
|
|
|
wgConfig := peer.WgConfig{
|
2022-01-10 18:43:13 +01:00
|
|
|
RemoteKey: pubKey,
|
2023-07-26 14:00:47 +02:00
|
|
|
WgListenPort: e.config.WgPort,
|
2022-01-17 14:01:58 +01:00
|
|
|
WgInterface: e.wgInterface,
|
2022-01-10 18:43:13 +01:00
|
|
|
AllowedIps: allowedIPs,
|
|
|
|
PreSharedKey: e.config.PreSharedKey,
|
|
|
|
}
|
|
|
|
|
|
|
|
// randomize connection timeout
|
|
|
|
timeout := time.Duration(rand.Intn(PeerConnectionTimeoutMax-PeerConnectionTimeoutMin)+PeerConnectionTimeoutMin) * time.Millisecond
|
|
|
|
config := peer.ConnConfig{
|
2022-11-23 11:03:29 +01:00
|
|
|
Key: pubKey,
|
|
|
|
LocalKey: e.config.WgPrivateKey.PublicKey().String(),
|
|
|
|
StunTurn: stunTurn,
|
|
|
|
InterfaceBlackList: e.config.IFaceBlackList,
|
|
|
|
DisableIPv6Discovery: e.config.DisableIPv6Discovery,
|
|
|
|
Timeout: timeout,
|
2023-05-03 14:47:44 +02:00
|
|
|
UDPMux: e.udpMux.UDPMuxDefault,
|
|
|
|
UDPMuxSrflx: e.udpMux,
|
2023-07-26 14:00:47 +02:00
|
|
|
WgConfig: wgConfig,
|
2022-11-23 11:03:29 +01:00
|
|
|
LocalWgPort: e.config.WgPort,
|
2022-11-26 13:29:50 +01:00
|
|
|
NATExternalIPs: e.parseNATExternalIPMappings(),
|
2023-04-13 17:00:01 +02:00
|
|
|
UserspaceBind: e.wgInterface.IsUserspaceBind(),
|
2022-01-10 18:43:13 +01:00
|
|
|
}
|
|
|
|
|
2023-07-26 14:00:47 +02:00
|
|
|
peerConn, err := peer.NewConn(config, e.statusRecorder, e.wgProxyFactory, e.mobileDep.TunAdapter, e.mobileDep.IFaceDiscover)
|
2022-01-10 18:43:13 +01:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
wgPubKey, err := wgtypes.ParseKey(pubKey)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2022-09-02 19:33:35 +02:00
|
|
|
signalOffer := func(offerAnswer peer.OfferAnswer) error {
|
|
|
|
return SignalOfferAnswer(offerAnswer, e.config.WgPrivateKey, wgPubKey, e.signal, false)
|
2022-01-10 18:43:13 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
signalCandidate := func(candidate ice.Candidate) error {
|
|
|
|
return signalCandidate(candidate, e.config.WgPrivateKey, wgPubKey, e.signal)
|
|
|
|
}
|
|
|
|
|
2022-09-02 19:33:35 +02:00
|
|
|
signalAnswer := func(offerAnswer peer.OfferAnswer) error {
|
|
|
|
return SignalOfferAnswer(offerAnswer, e.config.WgPrivateKey, wgPubKey, e.signal, true)
|
2022-01-10 18:43:13 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
peerConn.SetSignalCandidate(signalCandidate)
|
|
|
|
peerConn.SetSignalOffer(signalOffer)
|
|
|
|
peerConn.SetSignalAnswer(signalAnswer)
|
2023-03-16 16:46:17 +01:00
|
|
|
peerConn.SetSendSignalMessage(func(message *sProto.Message) error {
|
|
|
|
return sendSignal(message, e.signal)
|
|
|
|
})
|
2022-01-10 18:43:13 +01:00
|
|
|
|
|
|
|
return peerConn, nil
|
|
|
|
}
|
|
|
|
|
2021-08-15 16:56:26 +02:00
|
|
|
// receiveSignalEvents connects to the Signal Service event stream to negotiate connection with remote peers
|
|
|
|
func (e *Engine) receiveSignalEvents() {
|
2021-11-06 15:00:13 +01:00
|
|
|
go func() {
|
|
|
|
// connect to a stream of messages coming from the signal server
|
|
|
|
err := e.signal.Receive(func(msg *sProto.Message) error {
|
|
|
|
e.syncMsgMux.Lock()
|
|
|
|
defer e.syncMsgMux.Unlock()
|
2021-05-01 12:45:37 +02:00
|
|
|
|
2022-01-10 18:43:13 +01:00
|
|
|
conn := e.peerConns[msg.Key]
|
2021-11-06 15:00:13 +01:00
|
|
|
if conn == nil {
|
|
|
|
return fmt.Errorf("wrongly addressed message %s", msg.Key)
|
2021-05-01 12:45:37 +02:00
|
|
|
}
|
|
|
|
|
2021-11-06 15:00:13 +01:00
|
|
|
switch msg.GetBody().Type {
|
|
|
|
case sProto.Body_OFFER:
|
|
|
|
remoteCred, err := signal.UnMarshalCredential(msg)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2023-03-16 16:46:17 +01:00
|
|
|
|
|
|
|
conn.RegisterProtoSupportMeta(msg.Body.GetFeaturesSupported())
|
|
|
|
|
2022-09-02 19:33:35 +02:00
|
|
|
conn.OnRemoteOffer(peer.OfferAnswer{
|
|
|
|
IceCredentials: peer.IceCredentials{
|
|
|
|
UFrag: remoteCred.UFrag,
|
|
|
|
Pwd: remoteCred.Pwd,
|
|
|
|
},
|
|
|
|
WgListenPort: int(msg.GetBody().GetWgListenPort()),
|
|
|
|
Version: msg.GetBody().GetNetBirdVersion(),
|
2021-11-06 15:00:13 +01:00
|
|
|
})
|
|
|
|
case sProto.Body_ANSWER:
|
|
|
|
remoteCred, err := signal.UnMarshalCredential(msg)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2023-03-16 16:46:17 +01:00
|
|
|
|
|
|
|
conn.RegisterProtoSupportMeta(msg.Body.GetFeaturesSupported())
|
|
|
|
|
2022-09-02 19:33:35 +02:00
|
|
|
conn.OnRemoteAnswer(peer.OfferAnswer{
|
|
|
|
IceCredentials: peer.IceCredentials{
|
|
|
|
UFrag: remoteCred.UFrag,
|
|
|
|
Pwd: remoteCred.Pwd,
|
|
|
|
},
|
|
|
|
WgListenPort: int(msg.GetBody().GetWgListenPort()),
|
|
|
|
Version: msg.GetBody().GetNetBirdVersion(),
|
2021-11-06 15:00:13 +01:00
|
|
|
})
|
|
|
|
case sProto.Body_CANDIDATE:
|
|
|
|
candidate, err := ice.UnmarshalCandidate(msg.GetBody().Payload)
|
|
|
|
if err != nil {
|
|
|
|
log.Errorf("failed on parsing remote candidate %s -> %s", candidate, err)
|
|
|
|
return err
|
|
|
|
}
|
2022-01-10 18:43:13 +01:00
|
|
|
conn.OnRemoteCandidate(candidate)
|
2023-03-16 16:46:17 +01:00
|
|
|
case sProto.Body_MODE:
|
2021-05-01 12:45:37 +02:00
|
|
|
}
|
|
|
|
|
2021-11-06 15:00:13 +01:00
|
|
|
return nil
|
|
|
|
})
|
|
|
|
if err != nil {
|
|
|
|
// happens if signal is unavailable for a long time.
|
|
|
|
// We want to cancel the operation of the whole client
|
2022-03-08 14:47:55 +01:00
|
|
|
_ = CtxGetState(e.ctx).Wrap(ErrResetConnection)
|
2021-11-06 15:00:13 +01:00
|
|
|
e.cancel()
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}()
|
2021-05-01 12:45:37 +02:00
|
|
|
|
2021-11-06 15:00:13 +01:00
|
|
|
e.signal.WaitStreamConnected()
|
2021-05-01 12:45:37 +02:00
|
|
|
}
|
2022-11-23 08:42:12 +01:00
|
|
|
|
2022-11-26 13:29:50 +01:00
|
|
|
func (e *Engine) parseNATExternalIPMappings() []string {
|
2022-11-23 08:42:12 +01:00
|
|
|
var mappedIPs []string
|
|
|
|
var ignoredIFaces = make(map[string]interface{})
|
2022-11-26 13:29:50 +01:00
|
|
|
for _, iFace := range e.config.IFaceBlackList {
|
2022-11-23 08:42:12 +01:00
|
|
|
ignoredIFaces[iFace] = nil
|
|
|
|
}
|
|
|
|
for _, mapping := range e.config.NATExternalIPs {
|
|
|
|
var external, internal string
|
|
|
|
var externalIP, internalIP net.IP
|
|
|
|
var err error
|
2023-01-17 19:16:50 +01:00
|
|
|
|
2022-11-23 08:42:12 +01:00
|
|
|
split := strings.Split(mapping, "/")
|
|
|
|
if len(split) > 2 {
|
|
|
|
log.Warnf("ignoring invalid external mapping '%s', too many delimiters", mapping)
|
|
|
|
break
|
|
|
|
}
|
|
|
|
if len(split) > 1 {
|
|
|
|
internal = split[1]
|
|
|
|
internalIP = net.ParseIP(internal)
|
|
|
|
if internalIP == nil {
|
|
|
|
// not a properly formatted IP address, maybe it's interface name?
|
|
|
|
if _, present := ignoredIFaces[internal]; present {
|
|
|
|
log.Warnf("internal interface '%s' in blacklist, ignoring external mapping '%s'", internal, mapping)
|
|
|
|
break
|
|
|
|
}
|
|
|
|
internalIP, err = findIPFromInterfaceName(internal)
|
|
|
|
if err != nil {
|
|
|
|
log.Warnf("error finding interface IP for interface '%s', ignoring external mapping '%s': %v", internal, mapping, err)
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
external = split[0]
|
|
|
|
externalIP = net.ParseIP(external)
|
|
|
|
if externalIP == nil {
|
2023-01-17 19:16:50 +01:00
|
|
|
log.Warnf("invalid external IP, %s, ignoring external IP mapping '%s'", external, mapping)
|
2022-11-23 08:42:12 +01:00
|
|
|
break
|
|
|
|
}
|
2023-09-04 17:03:44 +02:00
|
|
|
mappedIP := externalIP.String()
|
|
|
|
if internalIP != nil {
|
|
|
|
mappedIP = mappedIP + "/" + internalIP.String()
|
2022-11-23 08:42:12 +01:00
|
|
|
}
|
2023-09-04 17:03:44 +02:00
|
|
|
mappedIPs = append(mappedIPs, mappedIP)
|
|
|
|
log.Infof("parsed external IP mapping of '%s' as '%s'", mapping, mappedIP)
|
2022-11-23 08:42:12 +01:00
|
|
|
}
|
|
|
|
if len(mappedIPs) != len(e.config.NATExternalIPs) {
|
|
|
|
log.Warnf("one or more external IP mappings failed to parse, ignoring all mappings")
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
return mappedIPs
|
|
|
|
}
|
|
|
|
|
2023-02-21 10:46:58 +01:00
|
|
|
func (e *Engine) close() {
|
2023-07-26 14:00:47 +02:00
|
|
|
if err := e.wgProxyFactory.Free(); err != nil {
|
|
|
|
log.Errorf("failed closing ebpf proxy: %s", err)
|
|
|
|
}
|
|
|
|
|
2023-02-21 10:46:58 +01:00
|
|
|
log.Debugf("removing Netbird interface %s", e.config.WgIfaceName)
|
|
|
|
if e.wgInterface != nil {
|
|
|
|
if err := e.wgInterface.Close(); err != nil {
|
|
|
|
log.Errorf("failed closing Netbird interface %s %v", e.config.WgIfaceName, err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if e.udpMux != nil {
|
|
|
|
if err := e.udpMux.Close(); err != nil {
|
|
|
|
log.Debugf("close udp mux: %v", err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if e.udpMuxConn != nil {
|
|
|
|
if err := e.udpMuxConn.Close(); err != nil {
|
|
|
|
log.Debugf("close udp mux connection: %v", err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if !isNil(e.sshServer) {
|
|
|
|
err := e.sshServer.Stop()
|
|
|
|
if err != nil {
|
|
|
|
log.Warnf("failed stopping the SSH server: %v", err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if e.routeManager != nil {
|
|
|
|
e.routeManager.Stop()
|
|
|
|
}
|
|
|
|
|
|
|
|
if e.dnsServer != nil {
|
|
|
|
e.dnsServer.Stop()
|
|
|
|
}
|
|
|
|
|
2023-05-29 16:00:18 +02:00
|
|
|
if e.acl != nil {
|
|
|
|
e.acl.Stop()
|
|
|
|
}
|
2023-02-21 10:46:58 +01:00
|
|
|
}
|
|
|
|
|
2023-07-14 21:56:22 +02:00
|
|
|
func (e *Engine) readInitialSettings() ([]*route.Route, error) {
|
2023-06-12 14:43:55 +02:00
|
|
|
netMap, err := e.mgmClient.GetNetworkMap()
|
2023-05-31 18:25:24 +02:00
|
|
|
if err != nil {
|
2023-07-14 21:56:22 +02:00
|
|
|
return nil, err
|
2023-05-31 18:25:24 +02:00
|
|
|
}
|
2023-06-12 14:43:55 +02:00
|
|
|
routes := toRoutes(netMap.GetRoutes())
|
2023-07-14 21:56:22 +02:00
|
|
|
return routes, nil
|
2023-05-31 18:25:24 +02:00
|
|
|
}
|
|
|
|
|
2022-11-23 08:42:12 +01:00
|
|
|
func findIPFromInterfaceName(ifaceName string) (net.IP, error) {
|
2022-11-26 13:29:50 +01:00
|
|
|
iface, err := net.InterfaceByName(ifaceName)
|
2022-11-23 08:42:12 +01:00
|
|
|
if err != nil {
|
2022-11-26 13:29:50 +01:00
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return findIPFromInterface(iface)
|
2022-11-23 08:42:12 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
func findIPFromInterface(iface *net.Interface) (net.IP, error) {
|
2022-11-26 13:29:50 +01:00
|
|
|
ifaceAddrs, err := iface.Addrs()
|
2022-11-23 08:42:12 +01:00
|
|
|
if err != nil {
|
2022-11-26 13:29:50 +01:00
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
for _, addr := range ifaceAddrs {
|
|
|
|
if ipv4Addr := addr.(*net.IPNet).IP.To4(); ipv4Addr != nil {
|
2022-11-23 08:42:12 +01:00
|
|
|
return ipv4Addr, nil
|
2022-11-26 13:29:50 +01:00
|
|
|
}
|
|
|
|
}
|
2022-11-23 08:42:12 +01:00
|
|
|
return nil, fmt.Errorf("interface %s don't have an ipv4 address", iface.Name)
|
2022-11-26 13:29:50 +01:00
|
|
|
}
|