2021-08-15 16:56:26 +02:00
|
|
|
package internal
|
2021-05-01 12:45:37 +02:00
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"github.com/cenkalti/backoff/v4"
|
2021-05-19 11:13:25 +02:00
|
|
|
ice "github.com/pion/ice/v2"
|
2021-05-01 12:45:37 +02:00
|
|
|
log "github.com/sirupsen/logrus"
|
|
|
|
"github.com/wiretrustee/wiretrustee/iface"
|
2021-08-15 16:56:26 +02:00
|
|
|
mgm "github.com/wiretrustee/wiretrustee/management/client"
|
|
|
|
mgmProto "github.com/wiretrustee/wiretrustee/management/proto"
|
2021-08-09 19:21:48 +02:00
|
|
|
signal "github.com/wiretrustee/wiretrustee/signal/client"
|
2021-05-01 12:45:37 +02:00
|
|
|
sProto "github.com/wiretrustee/wiretrustee/signal/proto"
|
|
|
|
"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
|
2021-08-15 16:56:26 +02:00
|
|
|
"strings"
|
2021-07-19 15:02:11 +02:00
|
|
|
"sync"
|
2021-05-01 12:45:37 +02:00
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
2021-07-19 15:02:11 +02:00
|
|
|
// PeerConnectionTimeout is a timeout of an initial connection attempt to a remote peer.
|
|
|
|
// E.g. this peer will wait PeerConnectionTimeout for the remote peer to respond, if not successful then it will retry the connection attempt.
|
|
|
|
const PeerConnectionTimeout = 60 * time.Second
|
|
|
|
|
2021-08-15 16:56:26 +02:00
|
|
|
// EngineConfig is a config for the Engine
|
|
|
|
type EngineConfig struct {
|
|
|
|
// StunsTurns is a list of STUN and TURN servers used by ICE
|
|
|
|
StunsTurns []*ice.URL
|
|
|
|
WgIface string
|
|
|
|
// WgAddr is a Wireguard local address (Wiretrustee Network IP)
|
|
|
|
WgAddr string
|
|
|
|
// WgPrivateKey is a Wireguard private key of our peer (it MUST never leave the machine)
|
|
|
|
WgPrivateKey wgtypes.Key
|
|
|
|
// IFaceBlackList is a list of network interfaces to ignore when discovering connection candidates (ICE related)
|
|
|
|
IFaceBlackList map[string]struct{}
|
|
|
|
}
|
|
|
|
|
|
|
|
// 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
|
2021-05-01 12:45:37 +02:00
|
|
|
signal *signal.Client
|
2021-08-15 16:56:26 +02:00
|
|
|
// mgmClient is a Management Service client
|
|
|
|
mgmClient *mgm.Client
|
|
|
|
// conns is a collection of remote peer connections indexed by local public key of the remote peers
|
2021-05-01 12:45:37 +02:00
|
|
|
conns map[string]*Connection
|
2021-08-15 16:56:26 +02:00
|
|
|
|
|
|
|
// peerMux is used to sync peer operations (e.g. open connection, peer removal)
|
|
|
|
peerMux *sync.Mutex
|
|
|
|
// syncMsgMux is used to guarantee sequential Management Service message processing
|
|
|
|
syncMsgMux *sync.Mutex
|
|
|
|
|
|
|
|
config *EngineConfig
|
|
|
|
|
|
|
|
// wgPort is a Wireguard local listen port
|
|
|
|
wgPort int
|
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
|
2021-08-15 16:56:26 +02:00
|
|
|
func NewEngine(signalClient *signal.Client, mgmClient *mgm.Client, config *EngineConfig) *Engine {
|
2021-05-01 12:45:37 +02:00
|
|
|
return &Engine{
|
2021-08-15 16:56:26 +02:00
|
|
|
signal: signalClient,
|
|
|
|
mgmClient: mgmClient,
|
|
|
|
conns: map[string]*Connection{},
|
|
|
|
peerMux: &sync.Mutex{},
|
|
|
|
syncMsgMux: &sync.Mutex{},
|
|
|
|
config: config,
|
2021-05-01 12:45:37 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-08-15 16:56:26 +02:00
|
|
|
// Start creates a new Wireguard tunnel interface and listens to events from Signal and Management services
|
|
|
|
// 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 {
|
|
|
|
|
|
|
|
wgIface := e.config.WgIface
|
|
|
|
wgAddr := e.config.WgAddr
|
|
|
|
myPrivateKey := e.config.WgPrivateKey
|
2021-05-01 12:45:37 +02:00
|
|
|
|
2021-08-15 16:56:26 +02:00
|
|
|
err := iface.Create(wgIface, wgAddr)
|
2021-05-01 12:45:37 +02:00
|
|
|
if err != nil {
|
2021-08-15 16:56:26 +02:00
|
|
|
log.Errorf("failed creating interface %s: [%s]", wgIface, err.Error())
|
2021-05-01 12:45:37 +02:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2021-08-15 16:56:26 +02:00
|
|
|
err = iface.Configure(wgIface, myPrivateKey.String())
|
2021-05-01 12:45:37 +02:00
|
|
|
if err != nil {
|
2021-08-15 16:56:26 +02:00
|
|
|
log.Errorf("failed configuring Wireguard interface [%s]: %s", wgIface, err.Error())
|
2021-05-01 12:45:37 +02:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2021-08-15 16:56:26 +02:00
|
|
|
port, err := iface.GetListenPort(wgIface)
|
2021-05-01 12:45:37 +02:00
|
|
|
if err != nil {
|
2021-08-15 16:56:26 +02:00
|
|
|
log.Errorf("failed getting Wireguard listen port [%s]: %s", wgIface, err.Error())
|
2021-05-01 12:45:37 +02:00
|
|
|
return err
|
|
|
|
}
|
2021-08-15 16:56:26 +02:00
|
|
|
e.wgPort = *port
|
2021-05-01 12:45:37 +02:00
|
|
|
|
2021-08-15 16:56:26 +02:00
|
|
|
e.receiveSignalEvents()
|
|
|
|
e.receiveManagementEvents()
|
2021-05-01 12:45:37 +02:00
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2021-08-15 16:56:26 +02:00
|
|
|
// initializePeer peer agent attempt to open connection
|
|
|
|
func (e *Engine) initializePeer(peer Peer) {
|
2021-07-19 15:02:11 +02:00
|
|
|
var backOff = &backoff.ExponentialBackOff{
|
|
|
|
InitialInterval: backoff.DefaultInitialInterval,
|
|
|
|
RandomizationFactor: backoff.DefaultRandomizationFactor,
|
|
|
|
Multiplier: backoff.DefaultMultiplier,
|
|
|
|
MaxInterval: 5 * time.Second,
|
|
|
|
MaxElapsedTime: time.Duration(0), //never stop
|
|
|
|
Stop: backoff.Stop,
|
|
|
|
Clock: backoff.SystemClock,
|
|
|
|
}
|
|
|
|
operation := func() error {
|
2021-08-15 16:56:26 +02:00
|
|
|
_, err := e.openPeerConnection(e.wgPort, e.config.WgPrivateKey, peer)
|
|
|
|
e.peerMux.Lock()
|
|
|
|
defer e.peerMux.Unlock()
|
2021-07-19 15:02:11 +02:00
|
|
|
if _, ok := e.conns[peer.WgPubKey]; !ok {
|
|
|
|
log.Infof("removing connection attempt with Peer: %v, not retrying", peer.WgPubKey)
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
log.Warnln(err)
|
|
|
|
log.Warnln("retrying connection because of error: ", err.Error())
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
err := backoff.Retry(operation, backOff)
|
|
|
|
if err != nil {
|
|
|
|
// should actually never happen
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-08-15 16:56:26 +02:00
|
|
|
func (e *Engine) removePeerConnections(peers []string) error {
|
|
|
|
e.peerMux.Lock()
|
|
|
|
defer e.peerMux.Unlock()
|
|
|
|
for _, peer := range peers {
|
|
|
|
err := e.removePeerConnection(peer)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// removePeerConnection closes existing peer connection and removes peer
|
|
|
|
func (e *Engine) removePeerConnection(peerKey string) error {
|
|
|
|
conn, exists := e.conns[peerKey]
|
2021-07-19 15:02:11 +02:00
|
|
|
if exists && conn != nil {
|
2021-08-15 16:56:26 +02:00
|
|
|
delete(e.conns, peerKey)
|
2021-07-19 15:02:11 +02:00
|
|
|
return conn.Close()
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// GetPeerConnectionStatus returns a connection Status or nil if peer connection wasn't found
|
|
|
|
func (e *Engine) GetPeerConnectionStatus(peerKey string) *Status {
|
2021-08-15 16:56:26 +02:00
|
|
|
e.peerMux.Lock()
|
|
|
|
defer e.peerMux.Unlock()
|
2021-07-19 15:02:11 +02:00
|
|
|
|
|
|
|
conn, exists := e.conns[peerKey]
|
|
|
|
if exists && conn != nil {
|
|
|
|
return &conn.Status
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2021-08-15 16:56:26 +02:00
|
|
|
// openPeerConnection opens a new remote peer connection
|
2021-05-01 12:45:37 +02:00
|
|
|
func (e *Engine) openPeerConnection(wgPort int, myKey wgtypes.Key, peer Peer) (*Connection, error) {
|
2021-08-15 16:56:26 +02:00
|
|
|
e.peerMux.Lock()
|
2021-05-01 12:45:37 +02:00
|
|
|
|
|
|
|
remoteKey, _ := wgtypes.ParseKey(peer.WgPubKey)
|
|
|
|
connConfig := &ConnConfig{
|
2021-05-19 11:13:25 +02:00
|
|
|
WgListenAddr: fmt.Sprintf("127.0.0.1:%d", wgPort),
|
2021-08-15 16:56:26 +02:00
|
|
|
WgPeerIP: e.config.WgAddr,
|
|
|
|
WgIface: e.config.WgIface,
|
2021-05-19 11:13:25 +02:00
|
|
|
WgAllowedIPs: peer.WgAllowedIps,
|
|
|
|
WgKey: myKey,
|
|
|
|
RemoteWgKey: remoteKey,
|
2021-08-15 16:56:26 +02:00
|
|
|
StunTurnURLS: e.config.StunsTurns,
|
|
|
|
iFaceBlackList: e.config.IFaceBlackList,
|
2021-05-01 12:45:37 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
signalOffer := func(uFrag string, pwd string) error {
|
|
|
|
return signalAuth(uFrag, pwd, myKey, remoteKey, e.signal, false)
|
|
|
|
}
|
|
|
|
|
|
|
|
signalAnswer := func(uFrag string, pwd string) error {
|
|
|
|
return signalAuth(uFrag, pwd, myKey, remoteKey, e.signal, true)
|
|
|
|
}
|
|
|
|
signalCandidate := func(candidate ice.Candidate) error {
|
|
|
|
return signalCandidate(candidate, myKey, remoteKey, e.signal)
|
|
|
|
}
|
|
|
|
conn := NewConnection(*connConfig, signalCandidate, signalOffer, signalAnswer)
|
|
|
|
e.conns[remoteKey.String()] = conn
|
2021-08-15 16:56:26 +02:00
|
|
|
e.peerMux.Unlock()
|
2021-07-19 15:02:11 +02:00
|
|
|
|
2021-05-01 12:45:37 +02:00
|
|
|
// blocks until the connection is open (or timeout)
|
2021-07-19 15:02:11 +02:00
|
|
|
err := conn.Open(PeerConnectionTimeout)
|
2021-05-01 12:45:37 +02:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return conn, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func signalCandidate(candidate ice.Candidate, myKey wgtypes.Key, remoteKey wgtypes.Key, s *signal.Client) error {
|
|
|
|
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 {
|
|
|
|
log.Errorf("failed signaling candidate to the remote peer %s %s", remoteKey.String(), err)
|
|
|
|
//todo ??
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func signalAuth(uFrag string, pwd string, 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
|
|
|
}
|
|
|
|
|
2021-05-01 18:29:59 +02:00
|
|
|
msg, err := signal.MarshalCredential(myKey, remoteKey, &signal.Credential{
|
2021-05-01 12:45:37 +02:00
|
|
|
UFrag: uFrag,
|
|
|
|
Pwd: pwd}, t)
|
2021-05-15 12:23:56 +02:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
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
|
|
|
|
}
|
|
|
|
|
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() {
|
|
|
|
|
|
|
|
log.Debugf("connecting to Management Service updates stream")
|
|
|
|
|
|
|
|
e.mgmClient.Sync(func(update *mgmProto.SyncResponse) error {
|
|
|
|
// todo handle changes of global settings (in update.GetWiretrusteeConfig())
|
|
|
|
// todo handle changes of peer settings (in update.GetPeerConfig())
|
|
|
|
|
|
|
|
e.syncMsgMux.Lock()
|
|
|
|
defer e.syncMsgMux.Unlock()
|
|
|
|
|
|
|
|
remotePeers := update.GetRemotePeers()
|
|
|
|
if len(remotePeers) != 0 {
|
|
|
|
|
|
|
|
remotePeerMap := make(map[string]struct{})
|
|
|
|
for _, peer := range remotePeers {
|
|
|
|
remotePeerMap[peer.GetWgPubKey()] = struct{}{}
|
|
|
|
}
|
|
|
|
|
|
|
|
//remove peers that are no longer available for us
|
|
|
|
toRemove := []string{}
|
|
|
|
for p := range e.conns {
|
|
|
|
if _, ok := remotePeerMap[p]; !ok {
|
|
|
|
toRemove = append(toRemove, p)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
err := e.removePeerConnections(toRemove)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// add new peers
|
|
|
|
for _, peer := range remotePeers {
|
|
|
|
peerKey := peer.GetWgPubKey()
|
|
|
|
peerIPs := peer.GetAllowedIps()
|
|
|
|
if _, ok := e.conns[peerKey]; !ok {
|
|
|
|
go e.initializePeer(Peer{
|
|
|
|
WgPubKey: peerKey,
|
|
|
|
WgAllowedIps: strings.Join(peerIPs, ","),
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
})
|
|
|
|
|
|
|
|
log.Infof("connected to Management Service updates stream")
|
|
|
|
}
|
|
|
|
|
|
|
|
// receiveSignalEvents connects to the Signal Service event stream to negotiate connection with remote peers
|
|
|
|
func (e *Engine) receiveSignalEvents() {
|
2021-05-01 12:45:37 +02:00
|
|
|
// connect to a stream of messages coming from the signal server
|
2021-05-05 10:40:53 +02:00
|
|
|
e.signal.Receive(func(msg *sProto.Message) error {
|
2021-05-01 12:45:37 +02:00
|
|
|
|
2021-08-15 16:56:26 +02:00
|
|
|
e.syncMsgMux.Lock()
|
|
|
|
defer e.syncMsgMux.Unlock()
|
|
|
|
|
2021-05-01 12:45:37 +02:00
|
|
|
conn := e.conns[msg.Key]
|
|
|
|
if conn == nil {
|
|
|
|
return fmt.Errorf("wrongly addressed message %s", msg.Key)
|
|
|
|
}
|
|
|
|
|
|
|
|
if conn.Config.RemoteWgKey.String() != msg.Key {
|
|
|
|
return fmt.Errorf("unknown peer %s", msg.Key)
|
|
|
|
}
|
|
|
|
|
2021-05-01 18:29:59 +02:00
|
|
|
switch msg.GetBody().Type {
|
|
|
|
case sProto.Body_OFFER:
|
2021-05-01 12:45:37 +02:00
|
|
|
remoteCred, err := signal.UnMarshalCredential(msg)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
err = conn.OnOffer(IceCredentials{
|
|
|
|
uFrag: remoteCred.UFrag,
|
|
|
|
pwd: remoteCred.Pwd,
|
|
|
|
})
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
2021-05-01 18:29:59 +02:00
|
|
|
case sProto.Body_ANSWER:
|
2021-05-01 12:45:37 +02:00
|
|
|
remoteCred, err := signal.UnMarshalCredential(msg)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
err = conn.OnAnswer(IceCredentials{
|
|
|
|
uFrag: remoteCred.UFrag,
|
|
|
|
pwd: remoteCred.Pwd,
|
|
|
|
})
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2021-05-01 18:29:59 +02:00
|
|
|
case sProto.Body_CANDIDATE:
|
2021-05-01 12:45:37 +02:00
|
|
|
|
2021-05-01 18:29:59 +02:00
|
|
|
candidate, err := ice.UnmarshalCandidate(msg.GetBody().Payload)
|
2021-05-01 12:45:37 +02:00
|
|
|
if err != nil {
|
|
|
|
log.Errorf("failed on parsing remote candidate %s -> %s", candidate, err)
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
err = conn.OnRemoteCandidate(candidate)
|
|
|
|
if err != nil {
|
|
|
|
log.Errorf("error handling CANDIATE from %s", msg.Key)
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
})
|
|
|
|
|
|
|
|
e.signal.WaitConnected()
|
|
|
|
}
|