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"
|
2024-05-07 18:50:34 +02:00
|
|
|
"errors"
|
2021-05-01 12:45:37 +02:00
|
|
|
"fmt"
|
2024-06-03 17:31:37 +02:00
|
|
|
"maps"
|
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-12-20 23:02:42 +01:00
|
|
|
"github.com/pion/ice/v3"
|
|
|
|
"github.com/pion/stun/v2"
|
2023-03-03 19:49:18 +01:00
|
|
|
log "github.com/sirupsen/logrus"
|
|
|
|
"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
|
|
|
|
|
2023-12-08 10:48:21 +01:00
|
|
|
"github.com/netbirdio/netbird/client/firewall"
|
|
|
|
"github.com/netbirdio/netbird/client/firewall/manager"
|
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"
|
2024-05-07 18:50:34 +02:00
|
|
|
"github.com/netbirdio/netbird/client/internal/networkmonitor"
|
2023-03-03 19:49:18 +01:00
|
|
|
"github.com/netbirdio/netbird/client/internal/peer"
|
2024-01-22 12:20:24 +01:00
|
|
|
"github.com/netbirdio/netbird/client/internal/relay"
|
2024-01-08 12:25:35 +01:00
|
|
|
"github.com/netbirdio/netbird/client/internal/rosenpass"
|
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"
|
2024-06-14 14:40:31 +02:00
|
|
|
relayClient "github.com/netbirdio/netbird/relay/client"
|
2023-03-03 19:49:18 +01:00
|
|
|
"github.com/netbirdio/netbird/route"
|
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
|
|
|
|
2024-05-07 18:50:34 +02:00
|
|
|
// NetworkMonitor is a flag to enable network monitoring
|
|
|
|
NetworkMonitor bool
|
|
|
|
|
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
|
2024-01-08 12:25:35 +01:00
|
|
|
|
2024-02-21 17:23:17 +01:00
|
|
|
RosenpassEnabled bool
|
|
|
|
RosenpassPermissive bool
|
2024-02-20 11:13:27 +01:00
|
|
|
|
|
|
|
ServerSSHAllowed bool
|
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
|
2024-04-03 11:11:46 +02:00
|
|
|
|
2024-04-08 18:56:52 +02:00
|
|
|
beforePeerHook peer.BeforeAddPeerHookFunc
|
|
|
|
afterPeerHook peer.AfterRemovePeerHookFunc
|
|
|
|
|
2024-01-08 12:25:35 +01:00
|
|
|
// rpManager is a Rosenpass manager
|
|
|
|
rpManager *rosenpass.Manager
|
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
|
2023-12-20 23:02:42 +01:00
|
|
|
STUNs []*stun.URI
|
2021-09-03 17:47:40 +02:00
|
|
|
// TURNs is a list of STUN servers used by ICE
|
2023-12-20 23:02:42 +01:00
|
|
|
TURNs []*stun.URI
|
2021-09-07 18:36:46 +02:00
|
|
|
|
2024-04-23 14:42:53 +02:00
|
|
|
// clientRoutes is the most recent list of clientRoutes received from the Management Service
|
2024-06-03 17:31:37 +02:00
|
|
|
clientRoutes route.HAMap
|
|
|
|
clientRoutesMu sync.RWMutex
|
2024-04-23 14:42:53 +02:00
|
|
|
|
2024-05-07 18:50:34 +02:00
|
|
|
clientCtx context.Context
|
|
|
|
clientCancel context.CancelFunc
|
2021-10-17 22:15:38 +02:00
|
|
|
|
2024-05-07 18:50:34 +02:00
|
|
|
ctx context.Context
|
|
|
|
cancel context.CancelFunc
|
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
|
|
|
|
2024-01-03 16:06:20 +01:00
|
|
|
udpMux *bind.UniversalUDPMuxDefault
|
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
|
|
|
|
2024-05-17 09:43:18 +02:00
|
|
|
networkMonitor *networkmonitor.NetworkMonitor
|
2024-05-07 18:50:34 +02:00
|
|
|
|
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
|
|
|
|
2023-12-08 10:48:21 +01:00
|
|
|
firewall manager.Manager
|
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
|
2024-01-22 12:20:24 +01:00
|
|
|
|
|
|
|
mgmProbe *Probe
|
|
|
|
signalProbe *Probe
|
|
|
|
relayProbe *Probe
|
|
|
|
wgProbe *Probe
|
2024-05-22 11:15:29 +02:00
|
|
|
|
|
|
|
wgConnWorker sync.WaitGroup
|
2024-06-14 14:40:31 +02:00
|
|
|
|
|
|
|
relayManager *relayClient.Manager
|
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(
|
2024-05-07 18:50:34 +02:00
|
|
|
clientCtx context.Context,
|
|
|
|
clientCancel context.CancelFunc,
|
2024-01-22 12:20:24 +01:00
|
|
|
signalClient signal.Client,
|
|
|
|
mgmClient mgm.Client,
|
2024-06-14 14:40:31 +02:00
|
|
|
relayManager *relayClient.Manager,
|
2024-01-22 12:20:24 +01:00
|
|
|
config *EngineConfig,
|
|
|
|
mobileDep MobileDependency,
|
|
|
|
statusRecorder *peer.Status,
|
2022-02-16 20:00:21 +01:00
|
|
|
) *Engine {
|
2024-01-22 12:20:24 +01:00
|
|
|
return NewEngineWithProbes(
|
2024-05-07 18:50:34 +02:00
|
|
|
clientCtx,
|
|
|
|
clientCancel,
|
2024-01-22 12:20:24 +01:00
|
|
|
signalClient,
|
|
|
|
mgmClient,
|
2024-06-14 14:40:31 +02:00
|
|
|
relayManager,
|
2024-01-22 12:20:24 +01:00
|
|
|
config,
|
|
|
|
mobileDep,
|
|
|
|
statusRecorder,
|
|
|
|
nil,
|
|
|
|
nil,
|
|
|
|
nil,
|
|
|
|
nil,
|
|
|
|
)
|
|
|
|
}
|
2023-07-26 14:00:47 +02:00
|
|
|
|
2024-01-22 12:20:24 +01:00
|
|
|
// NewEngineWithProbes creates a new Connection Engine with probes attached
|
|
|
|
func NewEngineWithProbes(
|
2024-05-07 18:50:34 +02:00
|
|
|
clientCtx context.Context,
|
|
|
|
clientCancel context.CancelFunc,
|
2024-01-22 12:20:24 +01:00
|
|
|
signalClient signal.Client,
|
|
|
|
mgmClient mgm.Client,
|
2024-06-14 14:40:31 +02:00
|
|
|
relayManager *relayClient.Manager,
|
2024-01-22 12:20:24 +01:00
|
|
|
config *EngineConfig,
|
|
|
|
mobileDep MobileDependency,
|
|
|
|
statusRecorder *peer.Status,
|
|
|
|
mgmProbe *Probe,
|
|
|
|
signalProbe *Probe,
|
|
|
|
relayProbe *Probe,
|
|
|
|
wgProbe *Probe,
|
|
|
|
) *Engine {
|
2024-05-07 18:50:34 +02:00
|
|
|
|
2021-05-01 12:45:37 +02:00
|
|
|
return &Engine{
|
2024-05-07 18:50:34 +02:00
|
|
|
clientCtx: clientCtx,
|
|
|
|
clientCancel: clientCancel,
|
2022-07-02 12:02:17 +02:00
|
|
|
signal: signalClient,
|
|
|
|
mgmClient: mgmClient,
|
2024-06-14 14:40:31 +02:00
|
|
|
relayManager: relayManager,
|
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,
|
2023-12-20 23:02:42 +01:00
|
|
|
STUNs: []*stun.URI{},
|
|
|
|
TURNs: []*stun.URI{},
|
2022-07-02 12:02:17 +02:00
|
|
|
networkSerial: 0,
|
|
|
|
sshServerFunc: nbssh.DefaultSSHServer,
|
|
|
|
statusRecorder: statusRecorder,
|
2024-01-22 12:20:24 +01:00
|
|
|
mgmProbe: mgmProbe,
|
|
|
|
signalProbe: signalProbe,
|
|
|
|
relayProbe: relayProbe,
|
|
|
|
wgProbe: wgProbe,
|
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()
|
|
|
|
|
2024-05-07 18:50:34 +02:00
|
|
|
if e.cancel != nil {
|
|
|
|
e.cancel()
|
|
|
|
}
|
|
|
|
|
|
|
|
// stopping network monitor first to avoid starting the engine again
|
2024-05-17 09:43:18 +02:00
|
|
|
if e.networkMonitor != nil {
|
|
|
|
e.networkMonitor.Stop()
|
|
|
|
}
|
|
|
|
log.Info("Network monitor: stopped")
|
2024-05-07 18:50:34 +02:00
|
|
|
|
2022-01-25 11:18:01 +01:00
|
|
|
err := e.removeAllPeers()
|
2021-10-17 22:15:38 +02:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2024-06-03 17:31:37 +02:00
|
|
|
e.clientRoutesMu.Lock()
|
2024-04-23 14:42:53 +02:00
|
|
|
e.clientRoutes = nil
|
2024-06-03 17:31:37 +02:00
|
|
|
e.clientRoutesMu.Unlock()
|
2024-04-23 14:42:53 +02:00
|
|
|
|
2022-03-13 15:16:16 +01:00
|
|
|
// very ugly but we want to remove peers from the WireGuard interface first before removing interface.
|
2024-05-07 18:50:34 +02:00
|
|
|
// Removing peers happens in the conn.Close() asynchronously
|
2022-03-13 15:16:16 +01:00
|
|
|
time.Sleep(500 * time.Millisecond)
|
|
|
|
|
2023-02-21 10:46:58 +01:00
|
|
|
e.close()
|
2024-05-22 11:15:29 +02:00
|
|
|
e.wgConnWorker.Wait()
|
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
|
|
|
|
2024-05-07 18:50:34 +02:00
|
|
|
if e.cancel != nil {
|
|
|
|
e.cancel()
|
|
|
|
}
|
|
|
|
e.ctx, e.cancel = context.WithCancel(e.clientCtx)
|
|
|
|
|
2024-05-15 09:10:57 +02:00
|
|
|
e.wgProxyFactory = wgproxy.NewFactory(e.ctx, e.config.WgPort)
|
2024-05-07 18:50:34 +02:00
|
|
|
|
2024-01-03 16:06:20 +01:00
|
|
|
wgIface, err := e.newWgIface()
|
2023-03-24 08:40:39 +01:00
|
|
|
if err != nil {
|
2024-03-21 16:49:28 +01:00
|
|
|
log.Errorf("failed creating wireguard interface instance %s: [%s]", e.config.WgIfaceName, err)
|
|
|
|
return fmt.Errorf("new wg interface: %w", err)
|
2022-02-16 20:00:21 +01:00
|
|
|
}
|
2024-01-03 16:06:20 +01:00
|
|
|
e.wgInterface = wgIface
|
2023-05-31 18:25:24 +02:00
|
|
|
|
2024-01-08 12:25:35 +01:00
|
|
|
if e.config.RosenpassEnabled {
|
|
|
|
log.Infof("rosenpass is enabled")
|
2024-02-21 17:23:17 +01:00
|
|
|
if e.config.RosenpassPermissive {
|
|
|
|
log.Infof("running rosenpass in permissive mode")
|
|
|
|
} else {
|
|
|
|
log.Infof("running rosenpass in strict mode")
|
|
|
|
}
|
2024-01-08 12:25:35 +01:00
|
|
|
e.rpManager, err = rosenpass.NewManager(e.config.PreSharedKey, e.config.WgIfaceName)
|
|
|
|
if err != nil {
|
2024-03-21 16:49:28 +01:00
|
|
|
return fmt.Errorf("create rosenpass manager: %w", err)
|
2024-01-08 12:25:35 +01:00
|
|
|
}
|
|
|
|
err := e.rpManager.Run()
|
|
|
|
if err != nil {
|
2024-03-21 16:49:28 +01:00
|
|
|
return fmt.Errorf("run rosenpass manager: %w", err)
|
2024-01-08 12:25:35 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-01-03 16:06:20 +01:00
|
|
|
initialRoutes, dnsServer, err := e.newDnsServer()
|
2022-02-16 20:00:21 +01:00
|
|
|
if err != nil {
|
2024-01-03 16:06:20 +01:00
|
|
|
e.close()
|
2024-03-21 16:49:28 +01:00
|
|
|
return fmt.Errorf("create dns server: %w", err)
|
2022-02-16 20:00:21 +01:00
|
|
|
}
|
2024-01-03 16:06:20 +01:00
|
|
|
e.dnsServer = dnsServer
|
2022-02-16 20:00:21 +01:00
|
|
|
|
2024-01-03 16:06:20 +01:00
|
|
|
e.routeManager = routemanager.NewManager(e.ctx, e.config.WgPrivateKey.PublicKey().String(), e.wgInterface, e.statusRecorder, initialRoutes)
|
2024-04-08 18:56:52 +02:00
|
|
|
beforePeerHook, afterPeerHook, err := e.routeManager.Init()
|
|
|
|
if err != nil {
|
|
|
|
log.Errorf("Failed to initialize route manager: %s", err)
|
|
|
|
} else {
|
|
|
|
e.beforePeerHook = beforePeerHook
|
|
|
|
e.afterPeerHook = afterPeerHook
|
|
|
|
}
|
|
|
|
|
2023-11-02 19:04:33 +01:00
|
|
|
e.routeManager.SetRouteChangeListener(e.mobileDep.NetworkChangeListener)
|
2023-05-31 18:25:24 +02:00
|
|
|
|
2024-01-03 16:06:20 +01:00
|
|
|
err = e.wgInterfaceCreate()
|
2021-05-01 12:45:37 +02:00
|
|
|
if err != nil {
|
2024-01-03 16:06:20 +01:00
|
|
|
log.Errorf("failed creating tunnel interface %s: [%s]", e.config.WgIfaceName, err.Error())
|
2023-02-21 10:46:58 +01:00
|
|
|
e.close()
|
2024-03-21 16:49:28 +01:00
|
|
|
return fmt.Errorf("create wg interface: %w", err)
|
2021-05-01 12:45:37 +02:00
|
|
|
}
|
|
|
|
|
2023-12-08 10:48:21 +01:00
|
|
|
e.firewall, err = firewall.NewFirewall(e.ctx, e.wgInterface)
|
|
|
|
if err != nil {
|
|
|
|
log.Errorf("failed creating firewall manager: %s", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
if e.firewall != nil && e.firewall.IsServerRouteSupported() {
|
|
|
|
err = e.routeManager.EnableServerRouter(e.firewall)
|
|
|
|
if err != nil {
|
|
|
|
e.close()
|
2024-03-21 16:49:28 +01:00
|
|
|
return fmt.Errorf("enable server router: %w", err)
|
2023-12-08 10:48:21 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-01-03 16:06:20 +01:00
|
|
|
e.udpMux, err = e.wgInterface.Up()
|
2021-05-01 12:45:37 +02:00
|
|
|
if err != nil {
|
2024-01-03 16:06:20 +01:00
|
|
|
log.Errorf("failed to pull up wgInterface [%s]: %s", e.wgInterface.Name(), err.Error())
|
2023-02-21 10:46:58 +01:00
|
|
|
e.close()
|
2024-03-21 16:49:28 +01:00
|
|
|
return fmt.Errorf("up wg interface: %w", err)
|
2021-05-01 12:45:37 +02:00
|
|
|
}
|
|
|
|
|
2023-12-08 10:48:21 +01:00
|
|
|
if e.firewall != nil {
|
|
|
|
e.acl = acl.NewDefaultManager(e.firewall)
|
2023-05-29 16:00:18 +02:00
|
|
|
}
|
|
|
|
|
2023-06-15 12:25:18 +02:00
|
|
|
err = e.dnsServer.Initialize()
|
|
|
|
if err != nil {
|
|
|
|
e.close()
|
2024-03-21 16:49:28 +01:00
|
|
|
return fmt.Errorf("initialize dns server: %w", err)
|
2023-06-13 09:20:29 +02:00
|
|
|
}
|
|
|
|
|
2021-08-15 16:56:26 +02:00
|
|
|
e.receiveSignalEvents()
|
|
|
|
e.receiveManagementEvents()
|
2024-01-22 12:20:24 +01:00
|
|
|
e.receiveProbeEvents()
|
2021-05-01 12:45:37 +02:00
|
|
|
|
2024-05-17 09:43:18 +02:00
|
|
|
// starting network monitor at the very last to avoid disruptions
|
|
|
|
e.startNetworkMonitor()
|
2024-05-07 18:50:34 +02:00
|
|
|
|
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
|
2024-01-08 12:25:35 +01:00
|
|
|
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
|
|
|
}
|
|
|
|
|
2024-06-14 14:40:31 +02:00
|
|
|
msg, err := signal.MarshalCredential(
|
|
|
|
myKey,
|
|
|
|
offerAnswer.WgListenPort,
|
|
|
|
remoteKey, &signal.Credential{
|
|
|
|
UFrag: offerAnswer.IceCredentials.UFrag,
|
|
|
|
Pwd: offerAnswer.IceCredentials.Pwd,
|
|
|
|
},
|
|
|
|
t,
|
|
|
|
offerAnswer.RosenpassPubKey,
|
|
|
|
offerAnswer.RosenpassAddr,
|
|
|
|
offerAnswer.RelaySrvAddress)
|
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
|
|
|
|
}
|
|
|
|
|
2024-06-14 14:40:31 +02:00
|
|
|
// todo update relay address in the relay manager
|
|
|
|
|
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 {
|
2024-02-21 17:23:17 +01:00
|
|
|
|
2024-02-20 11:13:27 +01:00
|
|
|
if !e.config.ServerSSHAllowed {
|
|
|
|
log.Warnf("running SSH server is not permitted")
|
|
|
|
return nil
|
|
|
|
} else {
|
2024-02-21 17:23:17 +01:00
|
|
|
|
2024-02-20 11:13:27 +01:00
|
|
|
if sshConf.GetSshEnabled() {
|
|
|
|
if runtime.GOOS == "windows" {
|
|
|
|
log.Warnf("running SSH server on Windows is not supported")
|
|
|
|
return nil
|
2022-06-23 17:04:53 +02:00
|
|
|
}
|
2024-02-20 11:13:27 +01:00
|
|
|
// start SSH server if it wasn't running
|
|
|
|
if isNil(e.sshServer) {
|
|
|
|
// nil sshServer means it has not yet been started
|
|
|
|
var err error
|
|
|
|
e.sshServer, err = e.sshServerFunc(e.config.SSHKey,
|
|
|
|
fmt.Sprintf("%s:%d", e.wgInterface.Address().IP.String(), nbssh.DefaultSSHPort))
|
2022-06-23 17:04:53 +02:00
|
|
|
if err != nil {
|
2024-02-20 11:13:27 +01:00
|
|
|
return err
|
2022-06-23 17:04:53 +02:00
|
|
|
}
|
2024-02-20 11:13:27 +01:00
|
|
|
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 if !isNil(e.sshServer) {
|
|
|
|
// Disable SSH server request, so stop it if it was running
|
|
|
|
err := e.sshServer.Stop()
|
|
|
|
if err != nil {
|
|
|
|
log.Warnf("failed to stop SSH server %v", err)
|
|
|
|
}
|
|
|
|
e.sshServer = nil
|
2022-06-23 17:04:53 +02:00
|
|
|
}
|
2024-02-20 11:13:27 +01:00
|
|
|
return nil
|
|
|
|
|
2022-06-23 17:04:53 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
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 {
|
2024-01-11 14:36:27 +01:00
|
|
|
log.Warnf("failed handling SSH server setup %v", err)
|
2022-06-23 17:04:53 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
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() {
|
2024-05-07 18:50:34 +02:00
|
|
|
err := e.mgmClient.Sync(e.ctx, e.handleSync)
|
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)
|
2024-05-07 18:50:34 +02:00
|
|
|
e.clientCancel()
|
2021-09-07 18:36:46 +02:00
|
|
|
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
|
|
|
|
}
|
2023-12-20 23:02:42 +01:00
|
|
|
var newSTUNs []*stun.URI
|
2021-09-03 17:47:40 +02:00
|
|
|
log.Debugf("got STUNs update from Management Service, updating")
|
2023-12-20 23:02:42 +01:00
|
|
|
for _, s := range stuns {
|
|
|
|
url, err := stun.ParseURI(s.Uri)
|
2021-09-03 17:47:40 +02:00
|
|
|
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
|
|
|
|
}
|
2023-12-20 23:02:42 +01:00
|
|
|
var newTURNs []*stun.URI
|
2021-09-03 17:47:40 +02:00
|
|
|
log.Debugf("got TURNs update from Management Service, updating")
|
|
|
|
for _, turn := range turns {
|
2023-12-20 23:02:42 +01:00
|
|
|
url, err := stun.ParseURI(turn.HostConfig.Uri)
|
2021-09-03 17:47:40 +02:00
|
|
|
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 {
|
2023-11-10 16:33:13 +01:00
|
|
|
log.Warnf("failed adding authorized key to SSH DefaultServer %v", err)
|
2022-06-23 17:04:53 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
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{}
|
|
|
|
}
|
2024-04-23 14:42:53 +02:00
|
|
|
|
|
|
|
_, clientRoutes, err := e.routeManager.UpdateRoutes(serial, toRoutes(protoRoutes))
|
2022-09-05 09:06:35 +02:00
|
|
|
if err != nil {
|
2024-04-23 14:42:53 +02:00
|
|
|
log.Errorf("failed to update clientRoutes, err: %v", err)
|
2022-09-05 09:06:35 +02:00
|
|
|
}
|
2021-09-03 17:47:40 +02:00
|
|
|
|
2024-06-03 17:31:37 +02:00
|
|
|
e.clientRoutesMu.Lock()
|
2024-04-23 14:42:53 +02:00
|
|
|
e.clientRoutes = clientRoutes
|
2024-06-03 17:31:37 +02:00
|
|
|
e.clientRoutesMu.Unlock()
|
2024-04-23 14:42:53 +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
|
|
|
}
|
2024-03-15 18:57:18 +01:00
|
|
|
|
2022-01-18 16:44:58 +01:00
|
|
|
e.networkSerial = serial
|
2024-01-08 12:25:35 +01:00
|
|
|
|
2024-03-15 18:57:18 +01:00
|
|
|
// Test received (upstream) servers for availability right away instead of upon usage.
|
|
|
|
// If no server of a server group responds this will disable the respective handler and retry later.
|
|
|
|
e.dnsServer.ProbeAvailability()
|
|
|
|
|
2022-01-18 16:44:58 +01:00
|
|
|
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{
|
2024-05-06 14:47:49 +02:00
|
|
|
ID: route.ID(protoRoute.ID),
|
2022-09-05 09:06:35 +02:00
|
|
|
Network: prefix,
|
2024-05-06 14:47:49 +02:00
|
|
|
NetID: route.NetID(protoRoute.NetID),
|
2022-09-05 09:06:35 +02:00
|
|
|
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{
|
2023-10-19 19:32:42 +02:00
|
|
|
Primary: nsGroup.GetPrimary(),
|
|
|
|
Domains: nsGroup.GetDomains(),
|
|
|
|
SearchDomainsEnabled: nsGroup.GetSearchDomainsEnabled(),
|
2022-11-07 15:38:21 +01:00
|
|
|
}
|
|
|
|
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(),
|
2024-04-11 22:12:23 +02:00
|
|
|
Mux: new(sync.RWMutex),
|
2023-03-07 10:17:25 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
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 {
|
2024-04-03 11:11:46 +02:00
|
|
|
return fmt.Errorf("create peer connection: %w", 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
|
|
|
|
2024-04-08 18:56:52 +02:00
|
|
|
if e.beforePeerHook != nil && e.afterPeerHook != nil {
|
|
|
|
conn.AddBeforeAddPeerHook(e.beforePeerHook)
|
|
|
|
conn.AddAfterRemovePeerHook(e.afterPeerHook)
|
|
|
|
}
|
|
|
|
|
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)
|
|
|
|
}
|
|
|
|
|
2024-05-22 11:15:29 +02:00
|
|
|
e.wgConnWorker.Add(1)
|
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) {
|
2024-05-22 11:15:29 +02:00
|
|
|
defer e.wgConnWorker.Done()
|
2022-01-10 18:43:13 +01:00
|
|
|
for {
|
|
|
|
|
|
|
|
// randomize starting time a bit
|
|
|
|
min := 500
|
|
|
|
max := 2000
|
2024-05-22 11:15:29 +02:00
|
|
|
duration := time.Duration(rand.Intn(max-min)+min) * time.Millisecond
|
|
|
|
select {
|
|
|
|
case <-e.ctx.Done():
|
|
|
|
return
|
|
|
|
case <-time.After(duration):
|
|
|
|
}
|
2022-01-10 18:43:13 +01:00
|
|
|
|
|
|
|
// 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()
|
|
|
|
|
2024-05-07 18:50:34 +02:00
|
|
|
err := conn.Open(e.ctx)
|
2022-01-10 18:43:13 +01:00
|
|
|
if err != nil {
|
|
|
|
log.Debugf("connection to peer %s failed: %v", peerKey, err)
|
2024-05-07 18:50:34 +02:00
|
|
|
var connectionClosedError *peer.ConnectionClosedError
|
|
|
|
switch {
|
|
|
|
case errors.As(err, &connectionClosedError):
|
2022-06-04 19:41:01 +02:00
|
|
|
// 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)
|
2023-12-20 23:02:42 +01:00
|
|
|
var stunTurn []*stun.URI
|
2022-01-10 18:43:13 +01:00
|
|
|
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,
|
|
|
|
}
|
|
|
|
|
2024-02-21 17:23:17 +01:00
|
|
|
if e.config.RosenpassEnabled && !e.config.RosenpassPermissive {
|
2024-01-08 12:25:35 +01:00
|
|
|
lk := []byte(e.config.WgPrivateKey.PublicKey().String())
|
|
|
|
rk := []byte(wgConfig.RemoteKey)
|
|
|
|
var keyInput []byte
|
|
|
|
if string(lk) > string(rk) {
|
|
|
|
//nolint:gocritic
|
|
|
|
keyInput = append(lk[:16], rk[:16]...)
|
|
|
|
} else {
|
|
|
|
//nolint:gocritic
|
|
|
|
keyInput = append(rk[:16], lk[:16]...)
|
|
|
|
}
|
|
|
|
|
|
|
|
key, err := wgtypes.NewKey(keyInput)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
wgConfig.PreSharedKey = &key
|
|
|
|
}
|
|
|
|
|
2022-01-10 18:43:13 +01:00
|
|
|
// 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(),
|
2024-01-08 12:25:35 +01:00
|
|
|
RosenpassPubKey: e.getRosenpassPubKey(),
|
|
|
|
RosenpassAddr: e.getRosenpassAddr(),
|
2022-01-10 18:43:13 +01:00
|
|
|
}
|
|
|
|
|
2024-06-14 14:40:31 +02:00
|
|
|
peerConn, err := peer.NewConn(config, e.statusRecorder, e.wgProxyFactory, e.mobileDep.TunAdapter, e.mobileDep.IFaceDiscover, e.relayManager)
|
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
|
|
|
|
2024-01-08 12:25:35 +01:00
|
|
|
if e.rpManager != nil {
|
|
|
|
|
|
|
|
peerConn.SetOnConnected(e.rpManager.OnConnected)
|
|
|
|
peerConn.SetOnDisconnected(e.rpManager.OnDisconnected)
|
|
|
|
}
|
|
|
|
|
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
|
2024-05-07 18:50:34 +02:00
|
|
|
err := e.signal.Receive(e.ctx, func(msg *sProto.Message) error {
|
2021-11-06 15:00:13 +01:00
|
|
|
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
|
|
|
|
2024-01-08 12:25:35 +01:00
|
|
|
var rosenpassPubKey []byte
|
|
|
|
rosenpassAddr := ""
|
|
|
|
if msg.GetBody().GetRosenpassConfig() != nil {
|
|
|
|
rosenpassPubKey = msg.GetBody().GetRosenpassConfig().GetRosenpassPubKey()
|
|
|
|
rosenpassAddr = msg.GetBody().GetRosenpassConfig().GetRosenpassServerAddr()
|
|
|
|
}
|
2022-09-02 19:33:35 +02:00
|
|
|
conn.OnRemoteOffer(peer.OfferAnswer{
|
|
|
|
IceCredentials: peer.IceCredentials{
|
|
|
|
UFrag: remoteCred.UFrag,
|
|
|
|
Pwd: remoteCred.Pwd,
|
|
|
|
},
|
2024-01-08 12:25:35 +01:00
|
|
|
WgListenPort: int(msg.GetBody().GetWgListenPort()),
|
|
|
|
Version: msg.GetBody().GetNetBirdVersion(),
|
|
|
|
RosenpassPubKey: rosenpassPubKey,
|
|
|
|
RosenpassAddr: rosenpassAddr,
|
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
|
|
|
|
2024-01-08 12:25:35 +01:00
|
|
|
var rosenpassPubKey []byte
|
|
|
|
rosenpassAddr := ""
|
|
|
|
if msg.GetBody().GetRosenpassConfig() != nil {
|
|
|
|
rosenpassPubKey = msg.GetBody().GetRosenpassConfig().GetRosenpassPubKey()
|
|
|
|
rosenpassAddr = msg.GetBody().GetRosenpassConfig().GetRosenpassServerAddr()
|
|
|
|
}
|
2022-09-02 19:33:35 +02:00
|
|
|
conn.OnRemoteAnswer(peer.OfferAnswer{
|
|
|
|
IceCredentials: peer.IceCredentials{
|
|
|
|
UFrag: remoteCred.UFrag,
|
|
|
|
Pwd: remoteCred.Pwd,
|
|
|
|
},
|
2024-01-08 12:25:35 +01:00
|
|
|
WgListenPort: int(msg.GetBody().GetWgListenPort()),
|
|
|
|
Version: msg.GetBody().GetNetBirdVersion(),
|
|
|
|
RosenpassPubKey: rosenpassPubKey,
|
|
|
|
RosenpassAddr: rosenpassAddr,
|
2024-06-14 14:40:31 +02:00
|
|
|
RelaySrvAddress: msg.GetBody().GetRelayServerAddress(),
|
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
|
|
|
|
}
|
2024-06-03 17:31:37 +02:00
|
|
|
|
|
|
|
conn.OnRemoteCandidate(candidate, e.GetClientRoutes())
|
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)
|
2024-05-07 18:50:34 +02:00
|
|
|
e.clientCancel()
|
2021-11-06 15:00:13 +01:00
|
|
|
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() {
|
2024-05-07 18:50:34 +02:00
|
|
|
if e.wgProxyFactory != nil {
|
|
|
|
if err := e.wgProxyFactory.Free(); err != nil {
|
|
|
|
log.Errorf("failed closing ebpf proxy: %s", err)
|
|
|
|
}
|
2023-07-26 14:00:47 +02:00
|
|
|
}
|
|
|
|
|
2024-01-30 09:58:56 +01:00
|
|
|
// stop/restore DNS first so dbus and friends don't complain because of a missing interface
|
|
|
|
if e.dnsServer != nil {
|
|
|
|
e.dnsServer.Stop()
|
2024-05-07 18:50:34 +02:00
|
|
|
e.dnsServer = nil
|
2024-01-30 09:58:56 +01:00
|
|
|
}
|
|
|
|
|
2024-04-03 11:11:46 +02:00
|
|
|
if e.routeManager != nil {
|
|
|
|
e.routeManager.Stop()
|
|
|
|
}
|
|
|
|
|
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 !isNil(e.sshServer) {
|
|
|
|
err := e.sshServer.Stop()
|
|
|
|
if err != nil {
|
|
|
|
log.Warnf("failed stopping the SSH server: %v", err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-12-08 10:48:21 +01:00
|
|
|
if e.firewall != nil {
|
|
|
|
err := e.firewall.Reset()
|
|
|
|
if err != nil {
|
|
|
|
log.Warnf("failed to reset firewall: %s", err)
|
|
|
|
}
|
2023-05-29 16:00:18 +02:00
|
|
|
}
|
2024-01-08 12:25:35 +01:00
|
|
|
|
|
|
|
if e.rpManager != nil {
|
|
|
|
_ = e.rpManager.Close()
|
|
|
|
}
|
2023-02-21 10:46:58 +01:00
|
|
|
}
|
|
|
|
|
2023-11-02 19:04:33 +01:00
|
|
|
func (e *Engine) readInitialSettings() ([]*route.Route, *nbdns.Config, 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-11-02 19:04:33 +01:00
|
|
|
return nil, nil, err
|
2023-05-31 18:25:24 +02:00
|
|
|
}
|
2023-06-12 14:43:55 +02:00
|
|
|
routes := toRoutes(netMap.GetRoutes())
|
2023-11-02 19:04:33 +01:00
|
|
|
dnsCfg := toDNSConfig(netMap.GetDNSConfig())
|
|
|
|
return routes, &dnsCfg, nil
|
2023-05-31 18:25:24 +02:00
|
|
|
}
|
|
|
|
|
2024-01-03 16:06:20 +01:00
|
|
|
func (e *Engine) newWgIface() (*iface.WGIface, error) {
|
|
|
|
transportNet, err := e.newStdNet()
|
|
|
|
if err != nil {
|
|
|
|
log.Errorf("failed to create pion's stdnet: %s", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
var mArgs *iface.MobileIFaceArguments
|
|
|
|
switch runtime.GOOS {
|
|
|
|
case "android":
|
|
|
|
mArgs = &iface.MobileIFaceArguments{
|
|
|
|
TunAdapter: e.mobileDep.TunAdapter,
|
|
|
|
TunFd: int(e.mobileDep.FileDescriptor),
|
|
|
|
}
|
|
|
|
case "ios":
|
|
|
|
mArgs = &iface.MobileIFaceArguments{
|
|
|
|
TunFd: int(e.mobileDep.FileDescriptor),
|
|
|
|
}
|
|
|
|
default:
|
|
|
|
}
|
|
|
|
|
|
|
|
return iface.NewWGIFace(e.config.WgIfaceName, e.config.WgAddr, e.config.WgPort, e.config.WgPrivateKey.String(), iface.DefaultMTU, transportNet, mArgs)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (e *Engine) wgInterfaceCreate() (err error) {
|
|
|
|
switch runtime.GOOS {
|
|
|
|
case "android":
|
|
|
|
err = e.wgInterface.CreateOnAndroid(e.routeManager.InitialRouteRange(), e.dnsServer.DnsIP(), e.dnsServer.SearchDomains())
|
|
|
|
case "ios":
|
|
|
|
e.mobileDep.NetworkChangeListener.SetInterfaceIP(e.config.WgAddr)
|
|
|
|
err = e.wgInterface.Create()
|
|
|
|
default:
|
|
|
|
err = e.wgInterface.Create()
|
|
|
|
}
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
func (e *Engine) newDnsServer() ([]*route.Route, dns.Server, error) {
|
|
|
|
// due to tests where we are using a mocked version of the DNS server
|
|
|
|
if e.dnsServer != nil {
|
|
|
|
return nil, e.dnsServer, nil
|
|
|
|
}
|
|
|
|
switch runtime.GOOS {
|
|
|
|
case "android":
|
|
|
|
routes, dnsConfig, err := e.readInitialSettings()
|
|
|
|
if err != nil {
|
|
|
|
return nil, nil, err
|
|
|
|
}
|
2024-03-12 19:06:16 +01:00
|
|
|
dnsServer := dns.NewDefaultServerPermanentUpstream(
|
|
|
|
e.ctx,
|
|
|
|
e.wgInterface,
|
|
|
|
e.mobileDep.HostDNSAddresses,
|
|
|
|
*dnsConfig,
|
|
|
|
e.mobileDep.NetworkChangeListener,
|
|
|
|
e.statusRecorder,
|
|
|
|
)
|
2024-01-03 16:06:20 +01:00
|
|
|
go e.mobileDep.DnsReadyListener.OnReady()
|
|
|
|
return routes, dnsServer, nil
|
|
|
|
case "ios":
|
2024-03-12 19:06:16 +01:00
|
|
|
dnsServer := dns.NewDefaultServerIos(e.ctx, e.wgInterface, e.mobileDep.DnsManager, e.statusRecorder)
|
2024-01-03 16:06:20 +01:00
|
|
|
return nil, dnsServer, nil
|
|
|
|
default:
|
2024-03-12 19:06:16 +01:00
|
|
|
dnsServer, err := dns.NewDefaultServer(e.ctx, e.wgInterface, e.config.CustomDNSAddress, e.statusRecorder)
|
2024-01-03 16:06:20 +01:00
|
|
|
if err != nil {
|
|
|
|
return nil, nil, err
|
|
|
|
}
|
|
|
|
return nil, dnsServer, nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-04-23 14:42:53 +02:00
|
|
|
// GetClientRoutes returns the current routes from the route map
|
2024-05-06 14:47:49 +02:00
|
|
|
func (e *Engine) GetClientRoutes() route.HAMap {
|
2024-06-03 17:31:37 +02:00
|
|
|
e.clientRoutesMu.RLock()
|
|
|
|
defer e.clientRoutesMu.RUnlock()
|
|
|
|
|
|
|
|
return maps.Clone(e.clientRoutes)
|
2024-04-23 14:42:53 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// GetClientRoutesWithNetID returns the current routes from the route map, but the keys consist of the network ID only
|
2024-05-06 14:47:49 +02:00
|
|
|
func (e *Engine) GetClientRoutesWithNetID() map[route.NetID][]*route.Route {
|
2024-06-03 17:31:37 +02:00
|
|
|
e.clientRoutesMu.RLock()
|
|
|
|
defer e.clientRoutesMu.RUnlock()
|
|
|
|
|
2024-05-06 14:47:49 +02:00
|
|
|
routes := make(map[route.NetID][]*route.Route, len(e.clientRoutes))
|
2024-04-23 14:42:53 +02:00
|
|
|
for id, v := range e.clientRoutes {
|
2024-05-06 14:47:49 +02:00
|
|
|
routes[id.NetID()] = v
|
2024-04-23 14:42:53 +02:00
|
|
|
}
|
|
|
|
return routes
|
|
|
|
}
|
|
|
|
|
|
|
|
// GetRouteManager returns the route manager
|
|
|
|
func (e *Engine) GetRouteManager() routemanager.Manager {
|
|
|
|
return e.routeManager
|
|
|
|
}
|
|
|
|
|
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
|
|
|
}
|
2024-01-08 12:25:35 +01:00
|
|
|
|
|
|
|
func (e *Engine) getRosenpassPubKey() []byte {
|
|
|
|
if e.rpManager != nil {
|
|
|
|
return e.rpManager.GetPubKey()
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (e *Engine) getRosenpassAddr() string {
|
|
|
|
if e.rpManager != nil {
|
|
|
|
return e.rpManager.GetAddress().String()
|
|
|
|
}
|
|
|
|
return ""
|
|
|
|
}
|
2024-01-22 12:20:24 +01:00
|
|
|
|
|
|
|
func (e *Engine) receiveProbeEvents() {
|
|
|
|
if e.signalProbe != nil {
|
|
|
|
go e.signalProbe.Receive(e.ctx, func() bool {
|
|
|
|
healthy := e.signal.IsHealthy()
|
|
|
|
log.Debugf("received signal probe request, healthy: %t", healthy)
|
|
|
|
return healthy
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
if e.mgmProbe != nil {
|
|
|
|
go e.mgmProbe.Receive(e.ctx, func() bool {
|
|
|
|
healthy := e.mgmClient.IsHealthy()
|
|
|
|
log.Debugf("received management probe request, healthy: %t", healthy)
|
|
|
|
return healthy
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
if e.relayProbe != nil {
|
|
|
|
go e.relayProbe.Receive(e.ctx, func() bool {
|
|
|
|
healthy := true
|
|
|
|
|
|
|
|
results := append(e.probeSTUNs(), e.probeTURNs()...)
|
|
|
|
e.statusRecorder.UpdateRelayStates(results)
|
|
|
|
|
|
|
|
// A single failed server will result in a "failed" probe
|
|
|
|
for _, res := range results {
|
|
|
|
if res.Err != nil {
|
|
|
|
healthy = false
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
log.Debugf("received relay probe request, healthy: %t", healthy)
|
|
|
|
return healthy
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
if e.wgProbe != nil {
|
|
|
|
go e.wgProbe.Receive(e.ctx, func() bool {
|
|
|
|
log.Debug("received wg probe request")
|
|
|
|
|
|
|
|
for _, peer := range e.peerConns {
|
|
|
|
key := peer.GetKey()
|
|
|
|
wgStats, err := peer.GetConf().WgConfig.WgInterface.GetStats(key)
|
|
|
|
if err != nil {
|
|
|
|
log.Debugf("failed to get wg stats for peer %s: %s", key, err)
|
|
|
|
}
|
|
|
|
// wgStats could be zero value, in which case we just reset the stats
|
2024-02-24 12:41:13 +01:00
|
|
|
if err := e.statusRecorder.UpdateWireGuardPeerState(key, wgStats); err != nil {
|
2024-01-22 12:20:24 +01:00
|
|
|
log.Debugf("failed to update wg stats for peer %s: %s", key, err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return true
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (e *Engine) probeSTUNs() []relay.ProbeResult {
|
|
|
|
return relay.ProbeAll(e.ctx, relay.ProbeSTUN, e.STUNs)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (e *Engine) probeTURNs() []relay.ProbeResult {
|
|
|
|
return relay.ProbeAll(e.ctx, relay.ProbeTURN, e.TURNs)
|
|
|
|
}
|
2024-05-17 09:43:18 +02:00
|
|
|
|
|
|
|
func (e *Engine) startNetworkMonitor() {
|
|
|
|
if !e.config.NetworkMonitor {
|
|
|
|
log.Infof("Network monitor is disabled, not starting")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
e.networkMonitor = networkmonitor.New()
|
|
|
|
go func() {
|
|
|
|
err := e.networkMonitor.Start(e.ctx, func() {
|
|
|
|
log.Infof("Network monitor detected network change, restarting engine")
|
|
|
|
if err := e.Stop(); err != nil {
|
|
|
|
log.Errorf("Failed to stop engine: %v", err)
|
|
|
|
}
|
|
|
|
if err := e.Start(); err != nil {
|
|
|
|
log.Errorf("Failed to start engine: %v", err)
|
|
|
|
}
|
|
|
|
})
|
|
|
|
if err != nil && !errors.Is(err, networkmonitor.ErrStopped) {
|
|
|
|
log.Errorf("Network monitor: %v", err)
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
}
|